unordered_map
程序员文章站
2022-05-12 23:31:21
...
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";
}
}
上一篇: VMworld 2011:VMware推出数据库即服务新模式
下一篇: 如何执行PHP脚本?