unordered_map_operator_at

unordered_map_operator_at (std::unordered_map::operator[] — 첨자 연산자)

std::unordered_map에서 operator[]를 써서 키에 해당하는 매핑값에 대한 참조를 얻는 멤버 함수예요. 키가 없으면 기본 구성된 매핑값을 삽입해요.

출처: cppreference

본문

시그니처는 다음과 같아요.

T& operator[]( const Key& key );            // (1)
T& operator[]( Key&& key );                 // (2) (since C++11)

key에 매핑된 값에 대한 참조를 반환해요. 그런 키가 없으면 삽입을 수행해요. 매핑된 값은 value-initialized돼요.

key_type은 CopyConstructible, mapped_type은 CopyConstructible과 DefaultConstructible이어야 해요.

반환값

매핑값에 대한 참조. 그 키가 없으면 새로 삽입된 원소의 매핑값에 대한 참조.

복잡도

평균 상수(amortized constant)예요.

참고

operator[]는 키가 없으면 항상 새 원소를 삽입하므로, 조회만 하려면 find()를 쓰는 게 좋아요.

예제

#include <iostream>
#include <unordered_map>
int main()
{
    std::unordered_map<int, char> m{{1, 'a'}};
    m[2] = 'b';        // 2가 없어 삽입 후 'b' 대입
    std::cout << m[1] << '\n';   // a
}

더 알아보기 (Learn more)

cppreference