std::map<Key,T,Compare,Allocator>::insert_or_assign
Min standard notice:
1,4) If a key equivalent to k already exists in the container, assigns std::forward
# 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
k: the key used both to look up and to insert if not foundhint: iterator to the position before which the new element will be insertedobj: the value to insert or assign
# 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);
}