C++数据结构map

参考博客:(99条消息) std map用法_alex1801的博客-CSDN博客_std::map用法

                  (99条消息) C++ map遍历_两鬓已不能斑白的博客-CSDN博客_c++ map 遍历

对于stl的容器,平时对于map用的相对较少,今天刷题的时候碰到了这个数据结构,记录一下

map的基础属性:

m.size(); // 实际数据的数据
m.max_size(); // 最大数据的数量
m.empty(); // 判断容器是否为空
Amap m1, m2; 
m1[1] = a1; 
m1[2] = a2; 
m1[3] = a3;
 
m2.insert(m1.begin(), m1.end()); 
Amap mp2(m1); // mp2是m1的副本(通过拷贝构造)
m2 = m1; // m2是mp1的副本(通过复制赋值)

插入,我一般这么用

m.insert(make_pair(2, "Two"));

若已存在该键值,再进行插入操作无效,不报错,只能通过赋值改变内容

map的迭代器

begin: 返回迭代器到开始(公共成员函数)
end: 返回迭代器到末尾(公共成员函数)
 
rbegin:返回反向迭代器到反向开始(公共成员函数)
rend: 返回反向迭代器到反向端(公共成员函数)
 
cbegin: 将const_iterator返回到开始(公共成员函数)
cend: 返回const_iterator末尾(公共成员函数)
crbegin: 返回const_reverse_iterator到反向开始(公共成员函数)
crend: 返回const_reverse_iterator到reverse end(公共成员函数)
map<int, string>::iteartor it
for (auto it = m.begin(); it != m.end(); ++it)
{
    cout << " first:" << it->first << " " << it->second << endl;
}

//当然遍历的时候这么做更好

#include <iostream>
#include <map>

using namespace std;

int main() {
    map<int, int> _map;
    _map[0] = 1;
    _map[1] = 2;
    _map[10] = 10;

    map<int, int>::iterator iter;
    iter = _map.begin();
    while(iter != _map.end()) {
        cout << iter->first << " : " << iter->second << endl;
        iter++;
    }

    // 也可以使用for循环遍历
    /*
    for(iter = _map.begin(); iter != _map.end(); iter++) {
        cout << iter->first << " : " << iter->second << endl;
    }
    */
    return 0;
}

上图为顺序迭代

下图为逆序迭代

for (auto it = m.rbegin(); it != m.rend(); ++it)
{
    cout << " first:" << it->first << " " << it->second << endl;
}

当你需要了解map中的key值是否存在时:

m.find(key) != m.end() // key值存在

auto it = m.find(1);
cout << " m.find: " << it->first << endl;

如果你需要移除key

m.eraser(key)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值