Today I found a pretty annoyance when using STL string class. The find function returns the index if it find the string, and string::npos if it does not. For example,
std::string str("joeliscrazy");
index = str.find("joes");
The find returns a type of string::size_type, which is size_t in most implementations. Now since size_type is unsigned, you no longer can write the following statement
if ( index < 0 ) { }
Unless you define index as a signed type, such as int.
Other string libraries (java, .Net and MFC) use signed type as index, thus avoid this problem. Since most modern platforms provide 32-bit integer, who on the earth require a unsigned int as string index?
Subscribe to:
Post Comments (Atom)
2 comments:
I think using a single value for a non-index allows to scan twice as much space than using the sign.
As an alternative you can use this I believe:
if ( index == 0xFFFFFFFF ) { }
or
if ( (char)index == -1 ) { }
Post a Comment