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 동등한(equivalent) 키가 존재하지 않으면, 제자리에서 생성된 value_type 객체를 삽입합니다.
다음에 해당함: return this - > try_emplace ( std:: forward < K > ( x ) ) . first - > second ; . 이 오버로드는 Compare transparent 인 경우에만 오버로드 해결에 참여합니다. 이를 통해 Key 인스턴스를 생성하지 않고 이 함수를 호출할 수 있습니다.

목차

매개변수

key - 검색할 요소의 키
x - 키와 투명하게 비교될 수 있는 임의 타입의 값

반환값

1,2) key 를 가진 요소가 존재하지 않을 경우 새 요소의 매핑된 값에 대한 참조. 그렇지 않을 경우 키가 key 와 동등한 기존 요소의 매핑된 값에 대한 참조.
3) 키가 값 x 와 동등하게 비교되는 요소가 존재하지 않았을 경우, 새 요소의 매핑된 값에 대한 참조. 그렇지 않을 경우, 키가 x 와 동등하게 비교되는 기존 요소의 매핑된 값에 대한 참조.

예외

어떤 연산에서 예외가 발생하면, 삽입은 아무런 효과도 가지지 않습니다.

복잡도

컨테이너 크기에 대해 로그 시간 복잡도를 가지며, 빈 요소의 삽입 비용(있는 경우)이 추가됩니다.

참고 사항

operator [ ] 는 키가 존재하지 않을 경우 삽입하기 때문에 non-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; // 기존 값 업데이트
    letter_counts['x'] = 9;  // 새 값 삽입
    println("after modifications it contains: ", letter_counts);
    // 각 단어의 발생 횟수 계산
    // (operator[]의 첫 호출은 카운터를 0으로 초기화)
    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'

참고 항목

범위 검사와 함께 지정된 요소에 접근
(public member function)
요소를 삽입하거나 키가 이미 존재하는 경우 현재 요소에 할당
(public member function)
키가 존재하지 않으면 제자리에서 삽입, 키가 존재하면 아무 작업도 수행하지 않음
(public member function)