c ++中的find_first_of给出了不同的值

Nic*_*lah 3 c++

在下面的代码中,我不明白为什么b是假的.

string s = "--p--";
cout << s.find_first_of("p") << endl; //prints 2
bool b = s.find_first_of("p")>-1;
cout << b << endl;  //prints 0 (why?)
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 8

s.find_first_of("p")返回size_t其是unsigned类型.

在评估之前,>运算符将转换-1为无符号类型s.find_first_of("p")>-1;.这就是C++的工作原理:如果一个接受两个参数的运算符遇到a signed和一个unsigned类型作为那些参数,那么signed一个转换为unsigned一个.

-1当转换为无符号类型时,将是一个大的正数.(事实上​​,它会回绕到最大值size_t.)

所以你的比较评估为false.

要检查字符是否不在字符串中,请使用 b = s.find_first_of("p") != string::npos;