std::unordered_map::operator[]
来自cppreference.com
< cpp | container | unordered map
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
T& operator[]( const Key& key ); |
(1) | (C++11 起) |
T& operator[]( Key&& key ); |
(2) | (C++11 起) |
插入一个新元素的容器,使用
1) key
的关键和默认构造映射值,并返回一个引用到新建成的映射值。如果key
关键的元素已经存在,没有执行插入和其对应的值,则返回一个参考.....原文:
Inserts a new element to the container using
key
as the key and default constructed mapped value and returns a reference to the newly constructed mapped value. If an element with key key
already exists, no insertion is performed and a reference to its mapped value is returned.从本质上讲,执行(insert(std::make_pair(key, T())).first)->second.
2) 原文:
Essentially performs (insert(std::make_pair(key, T())).first)->second.
从本质上讲,执行(insert(std::make_pair(std::move(key), T())).first)->second.
原文:
Essentially performs (insert(std::make_pair(std::move(key), T())).first)->second.
If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is higher than max_load_factor()*bucket_count().
目录 |
[编辑] 参数
key | - | 找到的元素的键
|
[编辑] 返回值
参考的新元素映射的值,如果没有元素存在的关键
key
。否则,将参考现有元素的映射值,则返回.原文:
Reference to the mapped value of the new element if no element with key
key
existed. Otherwise a reference to the mapped value of the existing element is returned.[编辑] 复杂性
Average case: constant, worst case: linear in size.
[编辑] 为例
本章尚未完成 原因:暂无示例 |
[编辑] 另请参阅
访问指定的元素,同时进行越界检查 (公共成员函数) |
[编辑] 示例
计算一个向量的字符串中的每个单词的发生.....
原文:
Counts the occurrences of each word in a vector of strings.
#include <string> #include <iostream> #include <vector> #include <unordered_map> int main() { std::vector<std::string> words = { "this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax" }; std::unordered_map<std::string,size_t> word_map; for (auto w : words) { ++word_map[w]; } for (auto elem : word_map) { std::cout << elem.second << " occurrences of word '" << elem.first << "'\n"; } }
输出:
1 occurrences of word 'hoax' 2 occurrences of word 'this' 2 occurrences of word 'a' 2 occurrences of word 'is' 1 occurrences of word 'not' 3 occurrences of word 'sentence'