命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | 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 - 要查找的元素的键
x - 可以与键透明比较的任何类型的值

[编辑] 返回值

1,2) 如果不存在键为 key 的元素,则返回对新元素的映射值的引用。 否则,返回对键等价于 key 的现有元素的映射值的引用。
3) 如果不存在键与值 x 比较等价的元素,则返回对新元素的映射值的引用。 否则,返回对键与 x 比较等价的现有元素的映射值的引用。

[编辑] 异常

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

[编辑] 复杂度

容器大小的对数,加上空元素的插入(如果有)的成本。

[编辑] 注解

operator[] 是非 const 的,因为它在键不存在时插入键。 如果不希望这种行为,或者容器是 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; // updates an existing value
    letter_counts['x'] = 9;  // inserts a new value
 
    println("after modifications it contains: ", letter_counts);
 
    // count the number of occurrences of each word
    // (the first call to operator[] initialized the counter with zero)
    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"]; // just inserts the pair {"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'

[编辑] 参见

访问带有边界检查的指定元素
(公共成员函数) [编辑]
插入元素,如果键已存在则赋值给当前元素
(公共成员函数) [编辑]
如果键不存在则就地插入,如果键存在则不执行任何操作
(公共成员函数) [编辑]