C++11 unordered_map

【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 的赋值方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值