键值对容器,在需要频繁快速查找时使用
map和multimap类
头文件:< map>
内部结构类似二叉树实现,在插入元素的时进行排序,所以不能替换特定位置的元素
map和multimap的差别在于能不能储存唯一的键
- 实例化:
std::map<keyType,valueType,Predicate=std::less<keyType>> Name;
std::multimap<keyType,valueType,Predicate=std::less<keyType>> Name;
//示例
// map and multimap key of type int to value of type string
map<int, string> mapIntToStr1;
multimap<int, string> mmapIntToStr1;
// map and multimap constructed as a copy of another
map<int, string> mapIntToStr2(mapIntToStr1);
multimap<int, string> mmapIntToStr2(mmapIntToStr1);
// map and multimap constructed given a part of another map or multimap
map<int, string> mapIntToStr3(mapIntToStr1.cbegin(),mapIntToStr1.cend());
multimap<int, string> mmapIntToStr3(mmapIntToStr1.cbegin(),mmapIntToStr1.cend());
第三个参数缺省使用std::less<>
- insert
插入的方式有:
3: MAP_INT_STRING mapIntToStr;
//typedef map <int, string> MAP_INT_STRING;
4:
5: // Insert key-value pairs into the map using value_type
6: mapIntToStr.insert (MAP_INT_STRING::value_type (3, "Three"));
7:
8: // Insert a pair using function make_pair
9: mapIntToStr.insert (make_pair (-1, "Minus One"));
10:
11: // Insert a pair object directly
12: mapIntToStr.insert (pair <int, string>(1000, "One Thousand"));
13:
14: // Use an array-like syntax for inserting key-value pairs
15: mapIntToStr [1000000] = "One Million";
- find
find成员函数,根据键查找值,返回一个迭代器,需要检查
示例:
35: auto pairFound = mapIntToStr.find(key);
36: if (pairFound != mapIntToStr.end())
37: {
38: cout << "Key " << pairFound->first << " points to Value: ";
39: cout << pairFound->second << endl;
40: }
41: else
42: cout << "Sorry, pair with key " << key << " not in map" << endl;
multimap可能会返回多个键值对
- erase
三种版本
//key
auto numPairsErased = mmapIntToStr.erase(-1);
//iterator
auto pair = mmapIntToStr.find(45);
if(pair != mmapIntToStr.end()){
mmapIntToStr.erase(pair);
}
// Erase a range from the multimap...
mmapIntToStr.erase(mmapIntToStr.lower_bound(1000),mmapIntToStr.upper_bound(1000) );
-
count
count(value),在multimap中返回容器中有多少个元素包含特定的值 -
排序谓词
结构:
template<typename keyType>
struct Predicate{
bool operator()(const keyType& key1, const keyType& key2){
// your sort priority logic here
}
};
- 散列函数类unordered_map、unordered_multimap
头文件:
< unordered_map> 平均插入和删除时间是固定的,查找元素的时间也是固定的,使用hash原理实现的
常用函数有:- insert()
- find()
- size()
- max_bucket_count()
- load_factor()
- max_load_factor()
注:当装载因子超过最大值的时候,会重新组织以增加桶数,并重建散列表