map_try_emplace
map_try_emplace (std::map::try_emplace — 있으면 유지, 없으면 제자리 삽입)
std::map에 키가 없을 때만 새 원소를 제자리 구성해 삽입하는 멤버 함수예요. 이미 있으면 아무것도 바꾸지 않아요. operator[]나 emplace와 달리 이미 있는 키의 매핑값을 건드리지 않아요.
출처: cppreference
본문
시그니처는 다음과 같아요 (모두 since C++17, 일부 C++26).
template< class... Args >
std::pair<iterator, bool> try_emplace( const Key& k, Args&&... args ); // (1)
template< class... Args >
std::pair<iterator, bool> try_emplace( Key&& k, Args&&... args ); // (2)
template< class K, class... Args >
std::pair<iterator, bool> try_emplace( K&& k, Args&&... args ); // (3) (since C++26)
template< class... Args >
iterator try_emplace( const_iterator hint, const Key& k, Args&&... args ); // (4)
template< class... Args >
iterator try_emplace( const_iterator hint, Key&& k, Args&&... args ); // (5)
(1,2,3) k(또는 x)와 동등한 키가 컨테이너에 없으면 std::forward<Args>(args)...로 구성한 mapped_type을 가진 원소를 삽입해요. 이미 있으면 삽입하지 않아요.
(4,5) 힌트 오버로드. hint 바로 앞에 최대한 가깝게 삽입해요.
try_emplace는 emplace와 달리 이미 같은 키가 있을 때 인자 args가 평가되지 않고, 매핑값이 이미 있으면 건드리지 않아요.
매개변수
k: 찾거나 삽입할 키hint: 새 원소가 삽입될 위치 바로 앞을 가리키는 이터레이터 (힌트 오버로드)args: 매핑값의 생성자에 전달할 인자들.
반환값
- (1,2,3)
{원소의 이터레이터, 새로 삽입됐으면 true}쌍. - (4,5) 원소의 이터레이터.
복잡도
로그(logarithmic)예요. 힌트 오버로드는 힌트가 적절하면 분할 상환 상수.
예제
#include <iostream>
#include <map>
#include <string>
int main()
{
std::map<int, std::string> m;
m.try_emplace(1, "a"); // 삽입
m.try_emplace(1, "b"); // 이미 있음, "b"는 안 만들어짐
std::cout << m[1] << '\n'; // a
}