While working on a project, I ran into the following issue I could not explain to myself.
I have the following is_in_set(..) function, which simply checks if a cstring is in an unordered_set of cstrings:
bool is_in_set(const char * str, std::unordered_set<const char *> the_set)
{
if ( the_set.find( str ) != the_set.end() )
return true;
else
return false;
}
And then I created the following sample main method to demonstrate my problem:
int main()
{
std::unordered_set<const char *> the_set({"one",
"two", "three", "four", "five"});
std::string str = "three";
const char * cstr = "three";
std::cout << "str in set? "
<< is_in_set( str.c_str() , the_set ) << std::endl
<< "cstr in set? "
<< is_in_set( cstr, the_set ) << std::endl;
const char * str_conv = str.c_str();
std::cout << "str_conv in set? "
<< is_in_set( str_conv , the_set ) << std::endl
<< "strcmp(str_conv, cstr) = " << strcmp( str_conv , cstr )
<< std::endl;
return 0;
}
I expected the above code to find the std::string casted to const char*, as well as the cstring in the set. Instead of that, it generates the following output (Visual Studio Community 2017):
str in set? 0
cstr in set? 1
str_conv in set? 0
strcmp(str_conv, cstr) = 0
I also ran a for-loop over both variables, outputting byte by byte (in hexadecimal representation) for each, which results in the following:
74 68 72 65 65 00 = c_str
74 68 72 65 65 00 = str_conv
Why is the std::string casted to const char * not being found in the set? Shouldn't strcmp return a value different from 0 in this case?