unordered_map与hash_map对比:
- unordered_map原来属于boost分支和std::tr1中,而hash_map属于非标准容器。
- unordered_map感觉速度和hash_map差不多,但是支持string做key,也可以使用复杂的对象作为key。
HashMap的定义
整形定义
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map <int, int> inthash;
inthash[1] = 123;
inthash[2] = 456;
int val1 = inthash[1];
int val2 = inthash[2];
cout << val1 << endl;
cout << val2 << endl;
}
字符型定义
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map <string, int> strhash;
strhash["a"] = 123;
strhash["b"] = 456;
int val1 = strhash["a"];
int val2 = strhash["b"];
cout << val1 << endl;
cout << val2 << endl;
}
HashMap的遍历
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<int, int> intHash;
intHash[1] = 123;
intHash[2] = 456;
intHash[3] = 789;
for (auto it = intHash.begin(); it != intHash.end(); ++it)
cout << " " << it->first << ":" << it->second << endl;
}
HashMap的查找
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<int, string> strHash;
strHash[12] = "123";
strHash[25] = "456";
strHash[39] = "789";
unordered_map<int, string>::iterator it = strHash.begin();
it = strHash.find(25);
if(it != strHash.end()){
cout << it->second << endl;
}else
{
cout << "not find" << endl;
}
}
显示HashMap的大小
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<string, string> strHash;
strHash["a"] = "123";
strHash["b"] = "456";
strHash["c"] = "789";
cout << strHash.size() << endl;
}
判断HashMap是否为空
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<const char*, string> strHash;
strHash["a"] = "123";
strHash["b"] = "456";
strHash["c"] = "789";
cout << strHash.empty() << endl;
}
删除HashMap中的元素
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<string, string> strHash;
strHash["a"] = "123";
strHash["b"] = "456";
strHash["c"] = "789";
strHash.erase("a");
unordered_map<string, string>::iterator it = strHash.begin();
while (it != strHash.end()){
cout<< it->first <<"\t" << it++->second <<endl;
}
}