std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: operator[]
|
T
&
operator
[
]
(
const
Key
&
key
)
;
|
(1) | (C++11부터) |
|
T
&
operator
[
]
(
Key
&&
key
)
;
|
(2) | (C++11부터) |
|
template
<
class
K
>
T & operator [ ] ( K && x ) ; |
(3) | (C++26부터) |
키가 key 또는 x 와 동등한 값에 매핑된 값의 참조를 반환하며, 해당 키가 아직 존재하지 않는 경우 삽입을 수행합니다.
value_type
객체를
std::
piecewise_construct
,
std::
forward_as_tuple
(
key
)
,
std::
tuple
<>
(
)
로부터 제자리에서 생성하여 삽입합니다.
key
로부터 복사 생성되고 매핑된 값은
값 초기화
됩니다.
-
value_type
은
EmplaceConstructible
이어야 하며 다음으로부터 생성 가능해야 함:
std::
piecewise_construct
,
std::
forward_as_tuple
(
key
)
,
std::
tuple
<>
(
)
. 기본 할당자를 사용할 경우, 이는
key_type
이
CopyConstructible
이어야 하고
mapped_type
이
DefaultConstructible
이어야 함을 의미합니다.
|
value_type
객체를
std::
piecewise_construct
,
std::
forward_as_tuple
(
std
::
move
(
key
)
)
,
std::
tuple
<>
(
)
로부터 제자리에서 생성하여 삽입합니다.
기본 할당자를 사용할 경우, 이로 인해 키가
key
로부터 이동 생성되고 매핑된 값은
값 초기화
됩니다.
-
value_type
은
EmplaceConstructible
이어야 하며, 다음으로부터 생성 가능해야 함:
std::
piecewise_construct
,
std::
forward_as_tuple
(
std
::
move
(
key
)
)
,
std::
tuple
<>
(
)
. 기본 할당자를 사용할 경우, 이는
key_type
이
MoveConstructible
이어야 하고
mapped_type
이
DefaultConstructible
이어야 함을 의미합니다.
|
Hash
와
KeyEqual
가 모두
transparent
인 경우에만 오버로드 해결에 참여합니다. 이는 해당
Hash
가
K
와
Key
타입 모두에 대해 호출 가능하고,
KeyEqual
가 투명하다는 것을 가정하며, 이를 통해
Key
의 인스턴스를 생성하지 않고 이 함수를 호출할 수 있습니다.
만약 연산 후 새로운 원소의 개수가 기존
max_load_factor()
*
bucket_count()
보다 크면 재해싱이 발생합니다.
재해싱이 발생하는 경우(삽입으로 인해), 모든 반복자는 무효화됩니다. 그렇지 않은 경우(재해싱 없음), 반복자는 무효화되지 않습니다.
목차 |
매개변수
| key | - | 검색할 요소의 키 |
| x | - | 키와 투명하게 비교될 수 있는 임의 타입의 값 |
반환값
예외
어떤 연산에서 예외가 발생하면, 삽입은 아무런 효과를 가지지 않습니다.
복잡도
평균 케이스: 상수, 최악의 케이스: 크기에 선형적.
참고 사항
발표된 C++11 및 C++14 표준에서 이 함수는
mapped_type
이(가)
DefaultInsertable
이고
key_type
이(가)
CopyInsertable
또는
MoveInsertable
이어야 한다고 명시되었습니다. 이 명세는 결함이 있었으며
LWG issue 2469
에 의해 수정되었으며, 위의 설명은 해당 이슈의 해결을 반영한 것입니다.
그러나 한 구현(libc++)은 표준 문서에 명시된 대로
key_type
와
mapped_type
객체를 두 개의 별도 할당자
construct()
호출을 통해 생성하는 것으로 알려져 있으며,
value_type
객체를 배치하는 방식보다는 이 방식을 사용합니다.
operator
[
]
는 키가 존재하지 않을 경우 삽입하기 때문에 non-const입니다. 이 동작이 바람직하지 않거나 컨테이너가
const
인 경우,
at
을 사용할 수 있습니다.
|
|
(C++17부터) |
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_associative_heterogeneous_insertion
|
202311L
|
(C++26) | 정렬 및 비정렬 연관 컨테이너 에서 남아있는 멤버 함수들에 대한 이종(heterogeneous) 오버로드. ( 3 ) |
예제
#include <iostream> #include <string> #include <unordered_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::unordered_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::unordered_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) |
|
|
(C++17)
|
요소를 삽입하거나 키가 이미 존재하는 경우 현재 요소에 할당
(public member function) |
|
(C++17)
|
키가 존재하지 않으면 제자리에서 삽입, 키가 존재하면 아무 작업도 수행하지 않음
(public member function) |