1.需要C++11
2.key相同時,[]方法賦值先來的value會被後來的覆蓋掉;而map.insert方法則不覆蓋先來的value直接返回;
使用map
輸入
#include <map>
#include <iostream>
#include <cassert>
int main(int argc, char **argv)
{
std::map<std::string, int> m;
m["hello"] = 23;
// check if key is present
if (m.find("world") != m.end())
std::cout << "map contains key world!\n";
// retrieve
std::cout << m["hello"] << '\n';
std::map<std::string, int>::iterator i = m.find("hello");
assert(i != m.end());
std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
return 0;
}
輸出
23
Key: hello Value: 23
使用hashmap只需要把以上的map全部替換爲unordered_map(包括頭文件)