【map 与 unordered_map 的区别】
std::map对应的数据结构是红黑树。红黑树是一种近似于平衡的二叉查找树,里面的数据是有序的。在红黑树上做查找、插入、删除操作的时间复杂度为O(logN)。而std::unordered_map对应哈希表,哈希表的特点就是查找效率高,时间复杂度为常数级别O(1), 而额外空间复杂度则要高出许多。所以对于需要高效率查询的情况,使用std::unordered_map容器,但是std::unordered_map对于迭代器遍历效率并不高。
而如果对内存大小比较敏感或者数据存储要求有序的话,则可以用std::map容器。
示例: vs 2012
int main()
{
// Create an empty unordered_map
std::unordered_map<std::string, int> wordMap;
// Insert Few elements in map
wordMap.insert( std::pair<std::string, int>( "First", 1 ));
wordMap.insert( std::pair<std::string, int>( "Second", 2 ));
//wordMap.insert (std::make_pair<std::string, int>("eggs",6));
/*wordMap.insert( { "Second", 2 });
wordMap.insert( { "Third", 3 });*/
// Overwrite value of an element
wordMap["Third"] = 8;
wordMap["Fourth"] ++;
std::cout << "==========================================" << std::endl;
// Iterate Over the unordered_map and display elements
for (std::pair<std::string, int> element : wordMap)
std::cout << element.first << " :: " << element.second << std::endl;
wordMap["Third"] = 654;
wordMap["Fourth"] = 10;
std::cout << "==========================================" << std::endl;
for (const auto& n : wordMap) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
wordMap["Fourth"] = 11;
std::cout << "==========================================" << std::endl;
std::cout << "[Fourth]" << wordMap["Fourth"] << std::endl; // 取值
std::cout << "==========================================" << std::endl;
return 0;
}
注意点: auto 的使用, map 的赋值方式