find_first_of in c++ gives different values -


in code below, don't understand why b false.

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?) 

s.find_first_of("p") returns size_t unsigned type.

the > operator convert -1 unsigned type before s.find_first_of("p")>-1; evaluated. that's how c++ works: if operator takes 2 arguments encounters signed , unsigned type arguments, signed 1 gets converted unsigned one.

-1 when converted unsigned type large positive number. (in fact, wrap around largest value of size_t.)

so comparison evaluates false.

to check if character not in string, use b = s.find_first_of("p") != string::npos;


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -