#include <map>
#include <iostream>
void print(const std::map<std::string, int> &m)
{
if (m.size() == 0)
{
std::cout << "null" << std::endl;
}
for (auto it : m)
{
std::cout << "key = " << it.first << " value = " << it.second << std::endl;
}
std::cout << "-------------------" << std::endl;
}
int main()
{
std::map<std::string, int> map_test;
// ----------------- 插入元素
// 方法 1
map_test.insert(std::map<std::string, int>::value_type("aaa", 1));
// 方法 2
map_test.insert(std::pair<std::string, int>("bbb", 2));
// 方法 3
map_test["ccc"] = 3;
print(map_test);
// ----------------- 删除元素
// 方法 1
map_test.erase("bbb");
print(map_test);
// 方法 2
std::map<std::string, int>::iterator key = map_test.find("ccc");
if (key != map_test.end())
{
map_test.erase(key);
}
print(map_test);
// 方法 3
map_test.erase(map_test.begin(), map_test.end());
print(map_test);
return 0;
}
结果
key = aaa value = 1
key = bbb value = 2
key = ccc value = 3
-------------------
key = aaa value = 1
key = ccc value = 3
-------------------
key = aaa value = 1
-------------------
null
-------------------
(SAW:Game Over!)