简体   繁体   中英

Different size of std::string::npos

I wrote a program which finds a character in a string with use of the find_last_of method.

// ...
unsigned found;
found = name.find_last_of(character);
if (found == std::string::npos) {
    std::cout << "NOT FOUND" << std::endl;
}
// ...

I've compiled the code on two machines, it works only on one of them (PC1). I've debugged it and found out, that std::string::npos is different for PC1 and PC2.

If no character is found then the value returned by the find_last_of == 4294967295 for both machines.

PC1:

std::string::npos == 4294967295

PC2:

std::string::npos == 18446744073709551615

Some more tests:

PC1:

sizeof(size_t) == 4

PC2:

sizeof(size_t) == 8

First machine is using a 32-bit operating system, second one a 64-bit operating system.

What should I use to compare the value returned by the find_last_of method to make it work on both machines?

What should I use to compare the value returned by the find_last_of method to make it work on both machines?

std::string::npos , and the type of the position ( found ) should be size_t .

The concrete size of the constant can be different on different architectures, but that is none of your concerns.

npos is a static member constant value with the greatest possible value for an element of type size_t.

Just look at the function - http://en.cppreference.com/w/cpp/string/basic_string/find_last_of :

size_type find_last_of( const basic_string& str, size_type pos = 0 ) const; (1)
size_type find_last_of( const CharT* s, size_type pos, size_type count ) const; (2)
size_type find_last_of( const CharT* s, size_type pos = 0 ) const; (3)
size_type find_last_of( CharT ch, size_type pos = 0 ) const; (4)

Obviously, std::string::size_type is the proper type to store the return value in, after which comparison with std::string::npos will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM