最近在学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是否相同:
2173

被折叠的 条评论
为什么被折叠?



