发现网上关于hashmap及map相关简单的操作内容较少,部分博客内容比较复杂不易理解,这里特意分享一个简单的教程。
1.at():根据Key值查找容器内元素,并返回map元素的引用。
e.g.
#include <iostream>
#include <string>
#include <map>
int main ()
{
std::map<std::string,int> mymap = {
{ "alpha", 0 },
{ "beta", 0 },
{ "gamma", 0 } };
mymap.at("alpha") = 10;
mymap.at("beta") = 20;
mymap.at("gamma") = 30;
for (auto& x: mymap) {
std::cout << x.first << ": " << x.second << '\n';
}
return 0;
}
2.访问元素:正向迭代和反向迭代。
begin():指向容器内的第一个元素的迭代器。迭代器访问元素时。
e.g.
hash.begin();
end(), rbegin(), rend()用法同上。
注意end()的返回值超出了map的最后一个值,应搭配hash.end() --;
3.hashmap的大小:size()成员函数;
重新置hashmap为空:clear()成员函数;
交换两个hashmap之间的元素:swap();
e.g.
hm1.swap(hm2);swap(hm1, hm2);
4.查找某个元素:find()成员函数;
判断是否为空:empty()成员函数;
统计hash_map中某个元素的个数:count( element );要么是1(即出现了该元素),要么是0(即没出现这样的元素).
erase():根据不同的索引擦除槽中的元素。
insert():插入元素。
e.g.哈希表常用操作代码示例:
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include <unordered_map>
#include <iostream>
//由于编译器报错,把hash_map换为了unordered_map
int main() {
using namespace std;
unordered_map <int, int> hm1;
unordered_map <int, int> ::const_iterator hm1_AcIter, hm1_RcIter;
typedef pair <int, int> Int_Pair;
hm1.insert(Int_Pair(1, 10));
hm1.insert(Int_Pair(2, 20));
hm1.insert(Int_Pair(3, 30));
hm1.insert(Int_Pair(5, 50));
hm1_RcIter = hm1.find( 2 );
cout << "Key值为2的哈希表中的值为: "
<< hm1_RcIter -> second << "." << endl;
//这里->second就是插入的第二个(2,20)中的第二个元素20,->first则为(2,20)中的2
// If no match is found for the key, end( ) is returned
hm1_RcIter = hm1.find(4);
//find()里搜索的是Key
if (hm1_RcIter == hm1.end())
cout << "哈希表中不存在Key值为4的元素. "<< endl;
else
cout << "Key值为4的元素值为: "
<< hm1_RcIter->second << "." << endl;
// The element at a specific location in the hash_map can be found
// using a dereferenced iterator addressing the location
hm1_AcIter = hm1.end();
//注意end()的返回值超出了map的最后一个元素,如果要用最后一个元素则应搭配hash.end() --;
hm1_AcIter --;
hm1_RcIter = hm1.find(hm1_AcIter->first);
cout << "哈希表中最后一个元素是: "
<< hm1_RcIter->second << "." << endl;
int x = hm1.count(5);
cout << "哈希表中是否存在索引为5的值:" << x << endl;
int size = hm1.size();
cout << "哈希表大小为:" << size << endl;
cin.get();
}