杨 波 wrote:
I am trying to use the ext/hash_map of gnu C++, but I observe some
strange behaviors, please help me, my code is :
bool SE::operator ()(const char *a, const char *b)
{
return strcmp(a, b);
}
I think you meant:
return strcmp(a, b) == 0;
hash_map<const char *, int, hash<const char *>, SE> map;
map["abc"] = 1;
map["ab"] = 10;
cout << map["abc"] << endl << map["ab"] << endl << map["d"] <<
endl;;
But to my surprise, all the three map["..."] output is '0'
In C++, there is rarely a good reason to represent strings as char
const*. Things will go a lot more smoothly if you just stick with a
string class, and use its c_str member function as needed. For example:
/* GNU */
#include <ext/hash_map>
/* C++ Standard */
#include <iostream>
#include <string>
namespace gnu = __gnu_cxx;
struct string_hash
{
std::size_t operator()(std::string const& s) const {
return gnu::hash<char const*>( )(s.c_str());
}
};
int main() {
gnu::hash_map<std::string, int, string_hash> map;
map["abc"] = 1;
map["ab"] = 10;
std::cout << map["abc"] << '\n';
std::cout << map["ab"] << '\n';
std::cout << map["d"] << '\n';
return 0;
}
_______________________________________________
help-gplusplus mailing list
[email protected]
http://lists.gnu.org/mailman/listinfo/help-gplusplus