C++语法之STL映射类

键值对容器,在需要频繁快速查找时使用

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原理实现的
    常用函数有:
    1. insert()
    2. find()
    3. size()
    4. max_bucket_count()
    5. load_factor()
    6. max_load_factor()
      注:当装载因子超过最大值的时候,会重新组织以增加桶数,并重建散列表
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值