Namespaces
Variants

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

From cppreference.net

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 起)

返回对映射到与 key x 等效的键所对应值的引用,若该键尚不存在则执行插入操作。

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 透明函数对象 时参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

目录

参数

key - 要查找元素的键
x - 可与键进行透明比较的任意类型值

返回值

1,2) 若不存在键为 key 的元素,则返回新元素映射值的引用。否则返回已存在且键等价于 key 的元素映射值的引用。
3) 若不存在与值 x 等效的键,则返回新元素映射值的引用。否则返回与 x 等效的既有元素映射值的引用。

异常

如果任何操作抛出异常,则插入操作不会产生任何效果。

复杂度

与容器大小成对数关系,加上(若发生)插入空元素的 插入操作 开销。

注释

operator [ ] 是非常量函数,因为它会在键不存在时执行插入操作。若需避免此行为或容器为 const 状态,可使用 at 方法。

insert_or_assign operator [ ] 返回更多信息,且不要求映射类型具有默认构造能力。

示例

#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 initially contains: ", letter_counts);
    letter_counts['b'] = 42; // 更新现有值
    letter_counts['x'] = 9;  // 插入新值
    println("after modifications it contains: ", 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 << count << " occurrence(s) of word '" << word << "'\n";
}

输出:

letter_counts initially contains: {{a: 27}{b: 3}{c: 1}}
after modifications it contains: {{a: 27}{b: 42}{c: 1}{x: 9}}
2 occurrence(s) of word 'a'
1 occurrence(s) of word 'hoax'
2 occurrence(s) of word 'is'
1 occurrence(s) of word 'not'
3 occurrence(s) of word 'sentence'
0 occurrence(s) of word 'that'
2 occurrence(s) of word 'this'

参见

访问指定元素并进行边界检查
(公开成员函数)
插入元素,若键已存在则赋值给当前元素
(公开成员函数)
若键不存在则就地插入,若键存在则不执行任何操作
(公开成员函数)