Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

unordered_map::operator[]

公众成员函数  <unordered_map>
mapped_type& operator[] ( const key_type& k );
mapped_type& operator[] ( key_type&& k );

访问元素

如果 k 与容器中元素的键匹配,则函数返回对其映射值的引用。

如果k与容器中任何元素的键不匹配,则函数将插入一个具有该键的新元素,并返回对其映射值的引用。 注意,这样总是会使容器的大小增加1,即使没有给元素赋映射值(元素是使用默认构造函数构造的)。

类似的成员函数unordered_map::at,当具有键的元素存在时具有相同的行为,但当键不存在时抛出异常。

☲  参数


K
访问其映射值的元素的键值。
成员类型key_type是存储在容器中的元素的键类型,在unordered_map中定义为其第一个模板参数(Key)的别名。
如果是右值(第二个版本),则在插入新元素时移动键而不是复制键。

☉  返回值



对键值等于k的元素映射值的引用。
成员类型unordered_mapped_type是容器中映射值的类型,在unordered_map中定义为它的第二个模板参数(T)的别名。
如果插入一个新元素,则使用allocator_traits<allocator_type>::construct()分配它的存储, 失败时可能抛出异常(对于默认分配器,如果分配请求不成功则抛出bad_alloc)。

☣  示例



// unordered_map::operator[]
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string> mymap;

  mymap["Bakery"]="Barbara";  // new element inserted
  mymap["Seafood"]="Lisa";    // new element inserted
  mymap["Produce"]="John";    // new element inserted

  std::string name = mymap["Bakery"];   // existing element accessed (read)
  mymap["Seafood"] = name;              // existing element accessed (written)

  mymap["Bakery"] = mymap["Produce"];   // existing elements accessed (read/written)

  name = mymap["Deli"];      // non-existing element: new element "Deli" inserted!

  mymap["Produce"] = mymap["Gifts"];    // new element "Gifts" inserted, "Produce" written

  for (auto& x: mymap) {
    std::cout << x.first << ": " << x.second << std::endl;
  }

  return 0;
}

输出:
Seafood: Barbara
Deli:
Bakery: John
Gifts:
Produce:

✥ 复杂度



平均情况下:常数。
最坏情况:容器大小呈线性。
如果插入了一个元素(不包括在上面的复杂性中),可能会触发rehash。


☣ 迭代器的有效性



在大多数情况下,容器中的所有迭代器在插入之后仍然有效。 例外的是当此函数插入一个新元素时,将强制进行重新哈希。在这种情况下,容器中的所有迭代器都失效。

如果插入操作后的新容器大小超过其容量阈值(计算方法为容器的bucket_count乘以其max_load_factor),则强制进行rehash。

对unordered_map容器中的元素的引用在所有情况下仍然有效,即使在重新散列之后也是如此。

🍄  另请参阅



unordered_map::find 获取元素迭代器(公众成员函数)
unordered_map::insert 插入元素(公众成员函数)
unordered_map::at 访问元素(公众成员函数)
unordered_map::emplace 构造和插入元素(公众成员函数)