map的一些细节

map是关联式容器,存放key-value,类型自定
map内部以二叉树的形式存放数据,所以查找的时候速度快。

  • map的定义
    map < int, string > mp
  • map赋值
    三种数据插入的方式,当map中存在key,insert插入失败,数组方式会覆盖原来的值。
// insert函数插入pair数据
map<int, string> mp;
mp.insert(pair<int, string>(1, "hello"));
// insert函数插入value_type数据
map<int, string> mp;
mp.insert(map<int, string>::value_type (1, "hello"));
// 数组方式插入
map<int, string> mp;
mp[1] = "hello";
  • map的大小
    mp.size()
  • 数据的遍历
for (auto it : mp)
    cout << it.first << " " << it.second << endl;
  • 数据的查找
// find
// 返回迭代器,不存在返回 mp.end()
mp.find(key);

// count
// 存在返回1, 不存在返回0
mp.count(key);

以前查找数据的时候,都是判断 mp[key] != 0, 后来做了一道题发现会超内存,有可能也会超时,因为用mp[key] 相当于先插入一个数据,然后初始值为0,所以数据多的时候回超内存或者超时。
以后还是老老实实的用 find 或者 count

猜你喜欢

转载自blog.csdn.net/henuyh/article/details/80577976