Posted on 2011-04-15 11:59
點點滴滴 閱讀(16101)
評論(0) 編輯 收藏 引用 所屬分類:
02 編程語言
int idx = str.find("abc");
if (idx == string::npos)
...
上述代碼中,idx的類型被定義為int,這是錯誤的,即使定義為 unsigned int 也是錯的,它必須定義為 string::size_type。
npos 是這樣定義的:
static const size_type npos = -1;
因為 string::size_type (由字符串配置器 allocator 定義) 描述的是 size,故需為無符號整數型別。因為缺省配置器以型別 size_t 作為 size_type,于是 -1 被轉換為無符號整數型別,npos 也就成了該型別的最大無符號值。不過實際數值還是取決于型別 size_type 的實際定義。不幸的是這些最大值都不相同。事實上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是兩者型別大小不同)。因此,比較式 idx == string::npos 中,如果 idx 的值為-1,由于 idx 和字符串string::npos 型別不同,比較結果可能得到 false。
要想判斷 find() 的結果是否為npos,最好的辦法是直接比較:
if (str.find("abc") == string::npos) { ... }
錯誤:if(str.find("abc") )
注:找不到abc會返回-1,不為0為True。0為False