C++的map是重载了"<",而unordered_map是重载了"==",所以对于自定义类型而言,要自己重载"=="运算符,当然还要自己写hash函数。string类型是不需要关注这两点的
class template
unordered_map
template < class Key, //unordered_map::key_type key类型
class T, //unordered_map::mapped_type value类型
class Hash = hash<Key>, // unordered_map::hasher hash函数
class Pred =equal_to<Key>, //unordered_map::key_equal 可以理解为相等判断的重载
class Alloc = allocator<pair<const Key,T> > // unordered_map::allocator_type 容器适配器,一般不用考虑
> class unordered_map;
#include <bits/stdc++.h>
using namespace std;
typedef unsigned int UL;
struct Cstr{
char s[8];
// Cstr(){ memset(s, 0, sizeof(s));}
// bool operator == (const Cstr& R)const{
// return strcmp(R.s, s) == 0;
// }//在这里进行 == 运算符重载也没有问题
friend istream& operator >> (istream& in, Cstr& str){
in >> str.s;
return in;
}
friend ostream& operator << (ostream& out, const Cstr& str){
out << str.s;
return out;
}
};
struct Equal{//比较函数
bool operator() (const Cstr& a, const Cstr& b)const{
return strcmp(a.s, b.s) == 0;
}
};
struct Hasher{//自定义hash函数
size_t operator()(const Cstr& str)const{//这里的size_t是32位无符号整型
size_t ans = 0, len = strlen(str.s);
for(int i = 0; i < len; ++i) ans = ans * 1007 + str.s[i];
return ans;
}
};
int main(){
unordered_map<Cstr, size_t, Hasher, Equal> wc;//如果重载了 "==" 运算符,就不需要加Equal了
//unordered_map<Cstr, size_t, Hasher> wc;//如果重载了 "==" 运算符,就不需要加Equal了
Cstr str;
while(cin >> str){
cout << str << endl;
++wc[str];
}
for(auto it : wc) cout << it.first << " " << it.second << endl;
return 0;
}
//统计单词个数