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

1,4) If a key equivalent to k already exists in the container, assigns std::forward(obj) to the mapped_type corresponding to the key k. If the key does not exist, inserts the new value as if by insert, constructing it from value_type(k, std::forward(obj)).

# Declarations

template< class M >
std::pair<iterator, bool> insert_or_assign( const Key& k, M&& obj );

(since C++17)

template< class M >
std::pair<iterator, bool> insert_or_assign( Key&& k, M&& obj );

(since C++17)

template< class K, class M >
std::pair<iterator, bool> insert_or_assign( K&& k, M&& obj );

(since C++26)

template< class M >
iterator insert_or_assign( const_iterator hint, const Key& k, M&& obj );

(since C++17)

template< class M >
iterator insert_or_assign( const_iterator hint, Key&& k, M&& obj );

(since C++17)

template< class K, class M >
iterator insert_or_assign( const_iterator hint, K&& k, M&& obj );

(since C++26)

# Parameters

# Notes

insert_or_assign returns more information than operator[] and does not require default-constructibility of the mapped type.

# Example

#include <iostream>
#include <string>
#include <map>
 
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::map<std::string, std::string> myMap;
 
    print_result(myMap.insert_or_assign("a", "apple"));
    print_result(myMap.insert_or_assign("b", "banana"));
    print_result(myMap.insert_or_assign("c", "cherry"));
    print_result(myMap.insert_or_assign("c", "clementine"));
 
    for (const auto& node : myMap)
        print_node(node);
}

# See also