Monthly Archives: October 2021

return 0 for std::string type

看到一段有問題的code,簡化如下 這樣子會compile過嗎? 答案是可以,此範例是可以通過compile。但是0是integer,integer和string應該不相容吧? 的確是不相容,其他的integer會compile不過,剛好 0 例外,在 C++11 4.10描述了 null pointer constant可以被轉成 null pointer 答案是可以,原因就在 std::string 接收 implicit construct from char pointer A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or … Continue reading

Posted in C++ Language | Leave a comment

stringstream使用

寫一個parser簡單的parse input,可以利用stringstream簡單做tokenizer 上面這個寫法看起來沒問題,檢查stringstream的state,如果fail就跳出迴圈,但其實這個寫法並不完全安全 我們再來看另一個範例 一般可能會預期就是印出1, 2, 3, 4, 5, 6的ascii int,但其實還多了一個-1 ,也就是說,在讀完6之後ss 的state還不是eof,等到做了peek()操作後,eof bit就會set了 因此在處理stringstream讀取時,此部分要特別小心,不能假設ss valid代表後面的讀操作就 會正確,還需要在讀操作後做一些檢查 以peek來說,C++11標準中描述的行為 int_type peek(); Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, reads but … Continue reading

Posted in C++ Language | Leave a comment

bits/stdc++.h

https://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c 有時候會看到一些範例使用 特別是在一些competitive programming中使用到,這個header基本上就是把所有的C++ header include進來,不用再特別去個別include 也可參考 https://gcc.gnu.org/onlinedocs/gcc-4.8.5/libstdc++/api/a01235_source.html 看起來省了好多include header的工,不過需要注意的是,這個header不是standard,所以使用上可能會有portable的issue 另可參考 https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h 這邊提出了一些pros and cons

Posted in C++ Language | Leave a comment