目录
七、一个key对应多个values unordered_multimap
简单对比map和unordered_map
map内部是红黑树,在插入元素时会自动排序,map中的元素会自动保持从小到大(key)排序存储.
而无序容器unordered_map内部是散列表,通过哈希而不是排序来快速操作元素,使得效率更高。当你不需要排序时选择unordered_map的效率更高。
一、头文件
#include <map> //注意,STL头文件没有扩展名.h
#include <unordered_map>
二、插入元素
// 定义一个map对象
map<int, string> mapFruit;
// 第一种 用insert函數插入pair
mapFruit.insert(pair<int, string>(1, "apple"));
// 第二种 用insert函数插入value_type数据
mapFruit.insert(map<int, string>::value_type(1, "orange"));
// 第三种 用"array"方式插入
mapFruit[5] = "banana";
mapFruit[8] = "watermelon";
用insert函数插入数据,当map中有这个关键字时,insert操作是不能再插入数据的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值。
用mapFruit[4]这种方式时,如果4不在map中,这样一调用就会自动创建了
三、查找元素
当所查找的关键key出现时,它返回数据所在对象的位置,如果沒有,返回iter与end函数的值相同。
// find 返回迭代器指向当前查找元素的位置否则返回map::end()位置
auto iter = mapFruit.find(5);
if(iter != mapFruit.end())
cout<<"Find, " << " the key = " << iter->first << " the value = " << iter->second <<endl;
else
cout<<"Do not Find"<<endl;
iter->first,iter->second 分别对应找到的key和values。
四、刪除与清空元素
//迭代器刪除
auto iter = mapFruit.find(4);
if(iter != mapFruit.end())
mapFruit.erase(iter);
//用关键字刪除
int n = mapFruit.erase(5);
cout << n << endl;//如果刪除了会返回1,否則返回0
//用迭代器范围刪除 : 把整个map清空
mapFruit.erase(mapFruit.begin(), mapFruit.end());
//等同于mapStudent.clear()
五、map遍历
// 应用前向迭代器
for(auto i =people.begin(); i != people.end();i++){
cout << i->first << '-' << people.at(i->first ) << endl;
}
// 应用反相迭代器,逆序输出,注意还是i++
for(auto i =people.rbegin(); i != people.rend();i++){
cout << i->first << '-' << people.at(i->first ) << endl;
}
六、map的基本操作函数
size() 返回map的大小
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
七、一个key对应多个values unordered_multimap
unordered_multimap<int, int> hashmap0;
hashmap0.insert(pair<int, int>(0, 1));
hashmap0.insert(pair<int, int>(0, 3));
hashmap0.insert(pair<int, int>(0, 2));
hashmap0.insert(pair<int, int>(1, 1));
hashmap0.insert(pair<int, int>(1, 2));
for(auto i = hashmap0.begin(); i != hashmap0.end(); i++){
cout << i -> first << ' ' << endl;
// unordered_multimap<int, int>::iterator m;
auto m = hashmap0.find(i -> first);
for(int k = 0; k != hashmap0.count(i -> first); k++,m++)
cout<<m->first<<"--"<<m->second<<endl;
}
key-vector<>的形式也是可以的