Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: try_emplace

From cppreference.net

template < class ... Args >
std:: pair < iterator, bool > try_emplace ( const Key & k, Args && ... args ) ;
(1) (C++17부터)
template < class ... Args >
std:: pair < iterator, bool > try_emplace ( Key && k, Args && ... args ) ;
(2) (C++17부터)
template < class K, class ... Args >
std:: pair < iterator, bool > try_emplace ( K && k, Args && ... args ) ;
(3) (C++26부터)
template < class ... Args >
iterator try_emplace ( const_iterator hint, const Key & k, Args && ... args ) ;
(4) (C++17부터)
template < class ... Args >
iterator try_emplace ( const_iterator hint, Key && k, Args && ... args ) ;
(5) (C++17부터)
template < class K, class ... Args >
iterator try_emplace ( const_iterator hint, K && k, Args && ... args ) ;
(6) (C++26부터)

만약 컨테이너에 k 와 동등한 키가 이미 존재하면, 아무 작업도 수행하지 않습니다. 그렇지 않으면, k 를 키로 하고 args 로 생성된 값을 가진 새 요소를 컨테이너에 삽입합니다. 이 경우:

1) emplace 와 유사하게 동작하지만, 요소가 다음과 같이 생성됩니다:
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( k ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
2) emplace 와 유사하게 동작하지만, 요소가 다음과 같이 생성됩니다:
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( std :: move ( k ) ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
3) emplace 와 유사하게 동작하지만, 요소가 다음과 같이 생성됩니다:
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( std:: forward < K > ( k ) ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
4) emplace_hint 와 동일하게 동작하지만, 요소가 다음과 같이 구성됩니다
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( k ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
5) emplace_hint 와 동일하게 동작하지만, 요소가 다음과 같이 구성됩니다:
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( std :: move ( k ) ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
6) emplace_hint 와 유사하게 동작하지만, 요소가 다음과 같이 구성됩니다:
value_type ( std:: piecewise_construct ,

std:: forward_as_tuple ( std:: forward < K > ( k ) ) ,

std:: forward_as_tuple ( std:: forward < Args > ( args ) ... ) )
1-6) 만약 value_type 이 해당 표현식으로부터 map EmplaceConstructible 가 아닌 경우, 동작은 정의되지 않습니다.
3) 이 오버로드는 다음의 모든 조건이 만족될 때에만 오버로드 해결에 참여합니다:
만약 equal_range ( u. first ) == equal_range ( k ) false 라면, 동작은 정의되지 않습니다. 여기서 u 는 삽입될 새 요소입니다.
6) 이 오버로드는 한정된 식별자 Compare :: is_transparent 가 유효하고 타입을 나타낼 때에만 오버로드 해결에 참여합니다.
만약 equal_range ( u. first ) == equal_range ( k ) false 라면, 동작은 정의되지 않습니다. 여기서 u 는 삽입될 새 요소입니다.

반복자나 참조가 무효화되지 않습니다.

목차

매개변수

k - 검색에 사용되며 찾지 못한 경우 삽입에 사용되는 키
hint - 새 요소가 삽입될 위치 바로 앞을 가리키는 반복자
args - 요소의 생성자로 전달할 인자들

반환값

1-3) emplace 와 동일함:
삽입된 요소(또는 삽입을 방해한 요소)에 대한 반복자와, 삽입이 발생한 경우에만 bool 값이 true 로 설정된 pair.
4-6) emplace_hint 와 동일:
삽입된 요소에 대한 반복자, 또는 삽입을 방해한 요소에 대한 반복자.

복잡도

1-3) emplace 와 동일:
컨테이너 크기에 대한 로그 시간 복잡도.
4-6) emplace_hint 와 동일:
일반적으로 컨테이너 크기에 대해 로그 시간이지만, 새 요소가 hint 바로 앞에 삽입되는 경우 분할 상환 상수 시간입니다.

참고 사항

insert emplace 와 달리, 이러한 함수들은 삽입이 발생하지 않을 경우 rvalue 인수로부터 이동을 수행하지 않습니다. 이로 인해 값이 이동 전용 타입인 맵(예: std:: map < std:: string , std:: unique_ptr < foo >> )을 쉽게 조작할 수 있습니다. 또한 try_emplace emplace 와 달리 키와 mapped_type 에 대한 인수를 별도로 처리합니다. emplace value_type (즉, std::pair )을 생성하기 위한 인수를 요구합니다.

오버로드 ( 3 ) ( 6 ) Key 타입의 객체를 생성하지 않고 호출할 수 있습니다.

기능 테스트 매크로 표준 기능
__cpp_lib_map_try_emplace 201411L (C++17) std::map::try_emplace , std::map::insert_or_assign
__cpp_lib_associative_heterogeneous_insertion 202311L (C++26) 연관 컨테이너의 나머지 멤버 함수에 대한 이종 오버로드 정렬된 비정렬 연관 컨테이너 . 오버로드 ( 3 ) ( 6 ) .

예제

#include <iostream>
#include <string>
#include <map>
#include <utility>
void print_node(const auto& node)
{
    std::cout << '[' << node.first << "] = " << node.second << '\n';
}
void print_result(auto const& pair)
{
    std::cout << (pair.second ? "inserted: " : "ignored:  ");
    print_node(*pair.first);
}
int main()
{
    using namespace std::literals;
    std::map<std::string, std::string> m;
    print_result(m.try_emplace("a", "a"s));
    print_result(m.try_emplace("b", "abcd"));
    print_result(m.try_emplace("c", 10, 'c'));
    print_result(m.try_emplace("c", "Won't be inserted"));
    for (const auto& p : m)
        print_node(p);
}

출력:

inserted: [a] = a
inserted: [b] = abcd
inserted: [c] = cccccccccc
ignored:  [c] = cccccccccc
[a] = a
[b] = abcd
[c] = cccccccccc

참고 항목

(C++11)
제자리에서 요소를 생성
(public member function)
힌트를 사용하여 제자리에서 요소 생성
(public member function)
요소 삽입 또는 노드 (since C++17)
(public member function)