'The return of string find function in cpp

Is there a case where the string::find function return -1 ? that code I have seen a lot while surveying a code for XML_Editor and I can't understand the code

if(temp.find("<") == -1){}

The above code is an example of what I mean I hope someone help , thanks :)



Solution 1:[1]

std::string::find returns npos when it cannot find its parameter. npos is defined as:

static const size_type npos = -1;

However, note that size_type is unsigned. Hence, one should not use -1 to check the value returend from find. The value of npos is the largest value representable as size_type and -1 is just a way to initialize npos with that value. When checking the value returned from find one should always use std::string::npos rather than -1, because -1 is a signed literal:

if(temp.find("<") == std::string::npos){
    // < was not found in temp
}

Solution 2:[2]

It would be more correct and clear to write

if(temp.find("<") == std::string::npos){}

where npos is usually defined like ( std::string::size_type )( -1 ). In the expression in the if statement

if(temp.find("<") == -1){}

the integer constant -1 having the type int is converted to the unsigned integer type std::string::size_type due to the usual arithmetic conversions and as such represents the maximum value for an object of the type std::string::size_type. This value signals that the operation was not successful.

Solution 3:[3]

std::string seems to return std::string::npos when it cannot find the input value, and std::string::npos is defined to be size_t(-1), but I think it's a better practice to use if(temp.find("<") == temp.npos){}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vlad from Moscow
Solution 3