STL:unordered_map使用笔记

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 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::value_type('f', 10));
	unordered_map::iterator its = letter_counts.begin();
	int s= letter_counts.count('s');
	int a = letter_counts.count('a');
	//letter_counts.erase(it);
	cout << s << a<  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";
	}
}

 

你可能感兴趣的:(C/C++)