嗨,我使用的hash_map为涉及字符串彼此,与此代码:的hash_map是节省每个键/值对即使当密钥是相同
#include <string>
#include <iostream>
#include <hash_map>
using namespace std;
using namespace stdext;
struct StrCompare : public stdext::hash_compare<string> {
unsigned int operator()(const string str) const {
unsigned int hash = 0;
unsigned int len = str.length();
for (unsigned int i = 0; i < len; i++)
hash = 31 * hash + str[i];
return hash;
}
bool operator()(const string str1, const string str2) const {
return str1 == str2;
}
};
int main() {
hash_map<string, string, StrCompare> m;
m["asdf"] = "fe";
m["asdf"] = "asdf";
for (hash_map<string, string, StrCompare>::iterator i = m.begin(); i != m.end(); ++i)
cout << i->first << " " << i->second << endl;
system("PAUSE");
}
的问题是,所述输出为:
asdf asdf
asdf fe
Press any key to continue . . .
这是怎么发生的?我曾尝试每次都打印哈希,但哈希是相同的。
那我该怎么做呢?我无法从你粘贴的信息中收集到什么。 – 2010-11-17 04:43:52
@James:我想你只需要'返回(str1
2010-11-17 18:46:54