std::map::insert(3)
π
std::map::insert β C++ Standard Library manual page, but make it bestie-core π
okay so we're deep in the std::map::insert(3) manual page from the C++ Standard Library, and this is part 1 of 2. buckle up, because inserting into a map is literally the main character move of associative containers β¨
πΈ NAME πΈ
std::map::insert - std::map::insert
yes bestie, it's the same thing twice. iconic behavior, no notes π
π SYNOPSIS π
std::pair<iterator, bool> insert( const value_type& value ); (1)
template< class P >
std::pair<iterator, bool> insert( P&& value ); (2) (since C++11)
std::pair<iterator, bool> insert( value_type&& value ); (3) (since C++17)
(4) iterator insert( iterator pos, const value_type& value ); (until C++11)
iterator insert( const_iterator pos, const value_type& value ); (since C++11)
template< class P >
iterator insert( const_iterator pos, P&& value ); (5) (since C++11)
iterator insert( const_iterator pos, value_type&& value ); (6) (since C++17)
template< class InputIt >
void insert( InputIt first, InputIt last ); (7)
void insert( std::initializer_list<value_type> ilist ); (8) (since C++11)
insert_return_type insert( node_type&& nh ); (9) (since C++17)
iterator insert( const_iterator pos, node_type&& nh ); (10) (since C++17)
π§ the tea: what insert actually does π§
Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key. no duplicates allowed, this map is exclusive π
1-3) Inserts value.
Overload (2) is equivalent to emplace(std::forward<P>(value)) and only participates in overload resolution if std::is_constructible<value_type, P&&>::value == true.
4-6) Inserts value in the position as close as possible to the position just prior to pos.
Overload (5) is equivalent to emplace_hint(hint, std::forward<P>(value)) and only participates in overload resolution if std::is_constructible<value_type, P&&>::value == true.
- Inserts elements from range
[first, last). If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending LWG2844). - Inserts elements from initializer list
ilist. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending LWG2844). - If
nhis an empty node handle, does nothing. Otherwise, inserts the element owned bynhinto the container, if the container doesn't already contain an element with a key equivalent tonh.key(). The behavior is undefined ifnhis not empty andget_allocator() != nh.get_allocator(). - If
nhis an empty node handle, does nothing and returns the end iterator. Otherwise, inserts the element owned bynhinto the container, if the container doesn't already contain an element with a key equivalent tonh.key(), and returns the iterator pointing to the element with key equivalent tonh.key()(regardless of whether the insert succeeded or failed). If the insertion succeeds,nhis moved from, otherwise it retains ownership of the element. The element is inserted as close as possible to the position just prior topos. The behavior is undefined ifnhis not empty andget_allocator() != nh.get_allocator().
No iterators or references are invalidated.
If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17)
π«Ά PARAMETERS π«Ά
posβ iterator to the position before which the new element will be insertedvalueβ element value to insertfirst,lastβ range of elements to insertilistβ initializer list to insert the values fromnhβ a compatible node handle
π§ TYPE REQUIREMENTS π§
InputItmust meet the requirements ofLegacyInputIterator.
π RETURN VALUE π
- 1-3) A pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a
boolvalue set totrueif and only if the insertion took place. - 4-6) An iterator to the inserted element, or to the element that prevented the insertion.
- 7,8) (none)
- 9) An object of
insert_return_typewith the members initialized as follows:- If
nhis empty,insertedisfalse,positionisend(), andnodeis empty. - Otherwise if the insertion took place,
insertedistrue,positionpoints to the inserted element, andnodeis empty. - If the insertion failed,
insertedisfalse,nodehas the previous value ofnh, andpositionpoints to an element with a key equivalent tonh.key().
- If
- 10) End iterator if
nhwas empty, iterator pointing to the inserted element if insertion took place, and iterator pointing to an element with a key equivalent tonh.key()if it failed.
π EXCEPTIONS π
- 1-6) If an exception is thrown by any operation, the insertion has no effect.
This section is incomplete Reason: cases 7-10
β‘ COMPLEXITY β‘
- 1-3) Logarithmic in the size of the container,
O(log(size())). - 4-6) Amortized constant if the insertion happens in the position just after (until C++11) before (since C++11)
pos, logarithmic in the size of the container otherwise. - 7,8)
O(NΒ·log(size() + N)), whereNis the number of elements to insert. - 9) Logarithmic in the size of the container,
O(log(size())). - 10) Amortized constant if the insertion happens in the position just before
pos, logarithmic in the size of the container otherwise.
ποΈ NOTES ποΈ
The hinted insert (4-6) does not return a boolean in order to be signature-compatible with positional insert on sequential containers, such as std::vector::insert. This makes it possible to create generic inserters such as std::inserter. One way to check success of a hinted insert is to compare size() before and after.
π EXAMPLE π
// Run this code
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
using namespace std::literals;
template<typename It>
void print_insertion_status(It it, bool success)
{
std::cout << "Insertion of " << it->first
<< (success ? " succeeded\n" : " failed\n");
}
int main()
{
std::map<std::string, float> heights;
// Overload 3: insert from rvalue reference
const auto [it_hinata, success] = heights.insert({"Hinata"s, 162.8});
print_insertion_status(it_hinata, success);
{
// Overload 1: insert from lvalue reference
const auto [it, success2] = heights.insert(*it_hinata);
print_insertion_status(it, success2);
}
{
// Overload 2: insert via forwarding to emplace
const auto [it, success] = heights.insert(std::pair{"Kageyama", 180.6});
print_insertion_status(it, success);
}
{
// Overload 6: insert from rvalue reference with positional hint
const std::size_t n = std::size(heights);
const auto it = heights.insert(it_hinata, {"Azumane"s, 184.7});
print_insertion_status(it, std::size(heights) != n);
}
{
// Overload 4: insert from lvalue reference with positional hint
const std::size_t n = std::size(heights);
const auto it = heights.insert(it_hinata, *it_hinata);
print_insertion_status(it, std::size(heights) != n);
}
{
// Overload 5: insert via forwarding to emplace with positional hint
const std::size_t n = std::size(heights);
const auto it = heights.insert(it_hinata, std::pair{"Tsukishima", 188.3});
print_insertion_status(it, std::size(heights) != n);
}
auto node_hinata = heights.extract(it_hinata);
std::map<std::string, float> heights2;
// Overload 7: insert from iterator range
heights2.insert(std::begin(heights), std::end(heights));
// Overload 8: insert from initializer_list
heights2.insert({{"Kozume"s, 169.2}, {"Kuroo", 187.7}});
// Overload 9: insert node
const auto status = heights2.insert(std::move(node_hinata));
print_insertion_status(status.position, status.inserted);
node_hinata = heights2.extract(status.position);
{
// Overload 10: insert node with positional hint
const std::size_t n = std::size(heights2);
const auto it = heights2.insert(std::begin(heights2), std::move(node_hinata));
print_insertion_status(it, std::size(heights2) != n);
}
// Print resulting map
std::cout << std::left << '\n';
for (const auto& [name, height] : heights2)
std::cout << std::setw(10) << name << " | " << height << "cm\n";
}
π OUTPUT π
Insertion of Hinata succeeded
Insertion of Hinata failed
Insertion of Kageyama succeeded
Insertion of Azumane succeeded
Insertion of Hinata failed
Insertion of Tsukishima succeeded
Insertion of Hinata succeeded
Insertion of Hinata succeeded
Azumane | 184.7cm
Hinata | 162.8cm
Kageyama | 180.6cm
Kozume | 169.2cm
Kuroo | 187.7cm
Tsukishima | 188.3cm
π DEFECT REPORTS π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
- LWG 233 β Applied to: C++98. Behavior as published:
poswas just a hint, it could be totally ignored. Correct behavior: the insertion is required to be as close as possible to the position just prior topos. - LWG 264 β Applied to: C++98. Behavior as published: the complexity of overload (7) was required to be linear if the range
[first, last)is sorted according toCompare. Correct behavior: removed the linear requirement in this special case. - LWG 316 β Applied to: C++98. Behavior as published: in the return value of overload (1), it was not specified which
boolvalue indicates a successful insertion. Correct behavior: success is indicated bytrue. - LWG 2005 β Applied to: C++11. Behavior as published: overloads (2,5) were poorly described. Correct behavior: improved the description.
β¨ SEE ALSO β¨
okay bestie these are the lil sibling functions you'll wanna meet too, they're all public member functions except the last one which is just a vibe:
emplaceβ constructs element in-place (C++11) (public member function)emplace_hintβ constructs elements in-place using a hint (C++11) (public member function)insert_or_assignβ inserts an element or assigns to the current element if the key already exists (C++17) (public member function)inserterβ creates astd::insert_iteratorof type inferred from the argument (function template)
π«Ά Category
- Todo with reason
no cap, that's literally just the category tag the page is filed under β an empty todo note with a reason attached, bestie. don't read into it π
and that's the whole page, you ate that π
β¨ go forth and insert responsibly, mwah π
source/version: http://cppreference.com Β· dated 2024.06.10 Β· page: std::map::insert(3) β periodt, she's iconic, bookmark her π π¦
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms