Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: insert_or_assign

From cppreference.net
template < class M >
std:: pair < iterator, bool > insert_or_assign ( const key_type & k, M && obj ) ;
(1) (C++23부터)
template < class M >
std:: pair < iterator, bool > insert_or_assign ( key_type && k, M && obj ) ;
(2) (C++23부터)
template < class K, class M >
std:: pair < iterator, bool > insert_or_assign ( K && k, M && obj ) ;
(3) (C++23부터)
template < class M >
iterator insert_or_assign ( const_iterator hint, const key_type & k, M && obj ) ;
(4) (C++23부터)
template < class M >
iterator insert_or_assign ( const_iterator hint, key_type && k, M && obj ) ;
(5) (C++23부터)
template < class K, class M >
iterator insert_or_assign ( const_iterator hint, K && k, M && obj ) ;
(6) (C++23부터)
1,2) 컨테이너에 이미 k 와 동등한 키가 존재하는 경우, std:: forward < M > ( obj ) 를 키 k 에 대응하는 mapped_type 에 할당합니다. 키가 존재하지 않는 경우, 다음처럼 새 값을 삽입합니다:
프로그램은 다음 중 하나라도 std:: is_assignable_v < mapped_type & , M > 또는 std:: is_constructible_v < mapped_type, M > false 인 경우 형식이 잘못되었습니다.
3,6) 컨테이너에 이미 k 와 동등한 키가 존재하는 경우, std:: forward < M > ( obj ) 를 키 k 에 해당하는 mapped_type 에 할당합니다. 그렇지 않은 경우, 다음에 해당합니다:
k 에서 key_type 으로의 변환은 객체 u 를 생성해야 하며, 이에 대해 find ( k ) == find ( u ) true 여야 합니다. 그렇지 않으면 동작은 정의되지 않습니다.
다음 오버로드들은 다음 조건에서만 오버로드 해결에 참여합니다:

목차

매개변수

k - 검색에 사용되며, 찾지 못한 경우 삽입에 사용되는 키
hint - 새 요소가 삽입될 위치 바로 앞을 가리키는 반복자
obj - 삽입 또는 할당할 값

반환값

1-3) bool 구성 요소는 삽입이 발생한 경우 true 이고 할당이 발생한 경우 false 입니다. 반복자 구성 요소는 삽입되거나 업데이트된 요소를 가리킵니다.
4-6) 삽입되거나 업데이트된 요소를 가리키는 반복자.

복잡도

1-3) emplace 와 동일합니다.
4-6) emplace_hint 와 동일합니다.

참고 사항

insert_or_assign operator [ ] 보다 더 많은 정보를 반환하며, 매핑된 타입의 기본 생성 가능성을 요구하지 않습니다.

예제

#include <flat_map>
#include <iostream>
#include <string>
void print_node(const auto& node)
{
    std::cout << '[' << node.first << "] = " << node.second << '\n';
}
void print_result(auto const& pair)
{
    std::cout << (pair.second ? "inserted: " : "assigned: ");
    print_node(*pair.first);
}
int main()
{
    std::flat_map<std::string, std::string> map;
    print_result(map.insert_or_assign("a", "apple"));
    print_result(map.insert_or_assign("b", "banana"));
    print_result(map.insert_or_assign("c", "cherry"));
    print_result(map.insert_or_assign("c", "clementine"));
    for (const auto& node : map)
        print_node(node);
}

출력:

inserted: [a] = apple
inserted: [b] = banana
inserted: [c] = cherry
assigned: [c] = clementine
[a] = apple
[b] = banana
[c] = clementine

참고 항목

지정된 요소에 접근하거나 삽입
(public member function)
범위 검사와 함께 지정된 요소에 접근
(public member function)
요소들을 삽입
(public member function)
제자리에서 요소를 생성
(public member function)
키가 존재하지 않으면 제자리에서 삽입, 키가 존재하면 아무 작업도 수행하지 않음
(public member function)