STL:unordered_map使用笔记

这篇博客介绍了STL中的unordered_map容器,重点强调了交换函数不会使内部迭代器失效,但会使得交换区域结束的迭代器失效。此外,指明了只有在删除元素时,元素的引用和指针才会失效。博主还分享了一个练习用的demo,并计划后续总结unordered_map的哈希桶实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The swap functions do not invalidate any of the iterators inside the container, but they do invalidate the iterator marking the end of the swap region. References and pointers to either key or data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated.

交换函数不会使容器内的任何迭代器失效,但会使标记交换区域结束的迭代器失效。

指向容器中存储的键或数据的引用和指针只有通过擦除该元素才无效,即使相应的迭代器无效。

下面是按照某文档随手敲得,练习的demo。过段时间归纳一下底层的哈希桶。

使用和map差不多,主要是因为无序的哈希,消耗内存更少一点。

void test_map()
{
	std::unordered_map<char, int> letter_counts{ {'a', 27}, {'b', 3}, {'c', 1} };
	auto it = letter_counts.find('c');
	letter_counts.insert(make_pair('d', 6));
	letter_counts['e'] = 10;
	letter_counts.insert(unordered_map<char, int>::value_type('f', 10));
	unordered_map<char, int>::iterator its = letter_counts.begin();
	int s= letter_counts.count('s');
	int a = letter_counts.count('a');
	//letter_counts.erase(it);
	cout << s << a<<endl;
	std::cout << "initially:\n";
	for (const auto &pair : letter_counts) {
		std::cout << pair.first << ": " << pair.second << '\n';
	}

	letter_counts['b'] = 42;  // update an existing value
	letter_counts['x'] = 9;  // insert a new value

	std::cout << "after modifications:\n";
	for (const auto &pair : letter_counts) {
		std::cout << pair.first << ": " << pair.second << '\n';
	}

	// count the number of occurrences of each word
	// (the first call to operator[] initialized the counter with zero)
	std::unordered_map<std::string, size_t>  word_map;
	for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
						   "this", "sentence", "is", "a", "hoax" }) {
		++word_map[w];
	}

	for (const auto &pair : word_map) {
		std::cout << pair.second << " occurrences of word '" << pair.first << "'\n";
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值