C++ map的使用


最近在学C++,想到Python中有字典,dictionary;C++中叫map,跟Java中的名字一样。

使用

想使用std::map,需要先#include <map>

使用方法如下:

#include <map>
int main(void){
    std::map<int,int> my_map={{1,1},{5,1}};//需要C++ 11
    return 0;
}

插入

map的插入方法如下:

std::map<int,int> my_map;
my_map[1]=1;
my_map.insert(std::pair<int, int>(2, 2));

如果一个key存在, operator[] 对这个key-value进行重写
如果一个key存在, insert 不会对原来的key-value进行重写

如果重复插入一样的值,C++的做法是忽略第二次的插入:

    std::cout << my_map.insert(std::pair<int, int>(2, 2)).second << std::endl;
    std::cout << my_map.insert(std::pair<int, int>(2, 2)).second << std::endl;

返回1表示插入成功,返回0表示插入失败。

更新

很多时候我们需要先读出值,然后更新。
参考:c++ - How to update std::map after using the find method? - Stack Overflow

传统做法是先查找,然后修改:

std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie

std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;

比较先进的做法是直接修改:

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

遍历map

map<string, int>::iterator it;

for ( it = symbolTable.begin(); it != symbolTable.end(); it++ )
{
    std::cout << it->first  // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl ;
}
for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl ;
}

比较2个map是否相同

需要自己写一个函数比较2个map是否相同:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值