we must use string::size_type for the return type of the find function, otherwise comparing with string::npos may not work. size_type , which is determined by the row dispenser, must be an unsigned integral type. The default dispenser, dispenser, uses the size_t type as size_type . Because -1 converted to an unsigned integral type, npos is the maximum unsigned value of its type. However, the exact value depends on the exact definition of type size_type . Unfortunately, these maximum values ββare different. In fact, (unsigned long)-1 is different from (unsigned short)- 1 if the size types are different. Thus comparing
idx == std::string::npos
can give false if idx is -1 , and idx and string::npos are different types:
std::string s; ... int idx = s.find("not found"); // assume it returns npos if (idx == std::string::npos) { // ERROR: comparison might not work ... }
One way to avoid this error is to check if the search worked directly:
if (s.find("hi") == std::string::npos) { ... }
However, often you need an index of the corresponding character position. So another simple solution is to define your own sign value for npos:
const int NPOS = -1;
Now the comparison looks a little different and even more convenient:
if (idx == NPOS) {
Debashish Mar 18 '15 at 7:43 2015-03-18 07:43
source share