Is size_t data type safe to use for str.find ()?

I was looking for code for a function find()for strings, and they store the result of this in a variable with the data type size_t. However, I understand that size_t is an unsigned int, and if it find()does not find the desired string, it returns -1. For example, if I have

string s = "asdf";
size_t i = s.find("g")
cout << i;

It gives me 4294967295. However, if I replace size_t with an int data type, it will give me -1. The strange thing is when I do a comparison, for example

string s = "asdf";
size_t i = s.find("g")
if (i == -1) { do_something; }

It works, be it size_t or int. So what am I using? int or size_t?

+4
source share
1 answer

None.

In the std::string::finddocumentation, it is recommended to use string::size_typeit string::nposfor detection not found in find:

 std::string::size_type i = s.find("g");
 if (i == std::string::npos) std::cout << "Not Found\n";

.

, int size_t -1 , , , , , :

: [-Wsign-compare]

+6

All Articles