std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::operator[]

来自cppreference.com
< cpp‎ | container‎ | flat map

 
 
 
 
T& operator[]( const Key& key );
(1) (C++23 起)
T& operator[]( Key&& key );
(2) (C++23 起)
template< class K >
T& operator[]( K&& x );
(3) (C++23 起)

返回到映射到分别等于 keyx 的键的值的引用,这种键不存在的情况下就会进行插入。

1) 在键不存在的情况下插入原位构造的 value_type 对象。等价于 return try_emplace(x).first->second;
2) 在键不存在的情况下插入原位构造的 value_type 对象。等价于 return try_emplace(std::move(x)).first->second;
3) 如果没有与 x 的值进行透明比较相等的键,则插入一个就地构造的 value_type 对象。
等价于 return this->try_emplace(std::forward<K>(x)).first->second;。 此重载仅在 此重载只有在限定标识 Compare::is_transparent 合法并指代类型时才会参与重载决议。它允许调用此函数时无需构造 Key 的实例。时参与重载决议。它允许调用该函数时无需构建 Key 的实例。

参数

key - 要寻找的元素键
x - 任何可以和键进行透明比较的类型的值

返回值

1,2) 不存在拥有键 key 的元素时返回到新元素被映射值的引用。否则返回指代其键等价于 key 的既存元素的被映射值的引用。
3) 不存在拥有与 x 值比较等价的键的元素时返回到新元素被映射值的引用。否则返回指代其键与 x 比较等价的既存元素的被映射值的引用。

异常

如果任何操作抛出异常,那么插入无效果。

复杂度

与容器大小成对数,加上插入一个空元素(如果有)的耗费。

注解

operator[] 非 const,因为它会在键不存在时插入键。如果此行为非所欲或容器为 const,那么可以使用 at

insert_or_assign 返回的信息多于 operator[],而且不要求 mapped_type 可默认构造。

示例

#include <iostream>
#include <string>
#include <flat_map>
 
void println(auto const comment, auto const& map)
{
    std::cout << comment << "{";
    for (const auto &pair : map)
        std::cout << "{" << pair.first << ": " << pair.second << "}";
    std::cout << "}\n";
}
 
int main()
{
    std::flat_map<char, int> letter_counts{{'a', 27}, {'b', 3}, {'c', 1}};
 
    println("letter_counts 起初包含:", letter_counts);
 
    letter_counts['b'] = 42; // 更新既存值
    letter_counts['x'] = 9;  // 插入新值
 
    println("修改后它包含:", letter_counts);
 
    // 统计每个单词的出现次数
    // (首次调用 operator[] 会初始化计数为零)
    std::flat_map<std::string, int>  word_map;
    for (const auto& w : {"this", "sentence", "is", "not", "a", "sentence",
                          "this", "sentence", "is", "a", "hoax"})
        ++word_map[w];
    word_map["that"]; // 插入对 {"that", 0}
 
    for (const auto& [word, count] : word_map)
        std::cout << "单词 '" << word << "' 出现 " << count << "次\n";
}

输出:

letter_counts 初始状态下包含:{{a: 27}{b: 3}{c: 1}}
修改后它包含:{{a: 27}{b: 42}{c: 1}{x: 9}}
单词 'a' 出现 2 次
单词 'hoax' 出现 1 次
单词 'is' 出现 2 次
单词 'not' 出现 1 次
单词 'sentence' 出现 3 次
单词 'that' 出现 0 次
单词 'this' 出现 2 次

参阅

带越界检查访问指定的元素
(公开成员函数)
插入元素,或若键已存在则赋值给当前元素
(公开成员函数)
若键不存在则原位插入,若键存在则不做任何事
(公开成员函数)