CKTIS / C++
Structured binding of a `std::map::insert` result (since C++17)
Use `auto [it, inserted]` to name the iterator and insertion flag returned by `std::map::insert` when inserting a single value without a position hint.
Version: ISO C++23; implementation support may vary
Syntax
auto [it, inserted] = m.insert(value); // C++17 and later; m is a std::map and value is a single elementSince C++17, auto [it, inserted] = m.insert(value); names both components of the returned pair. The brackets contain identifiers, not types: literal auto [iterator, bool] is a compile-time error because bool is a keyword. This pair requires exactly two names, in that order.
auto applies to a hidden pair object, not to two independent declarations. std::pair binds through its tuple-like interface: it names the first component (first), and inserted names the second (second). Given an existing pair result, auto [it, inserted] = result; copies it, whereas auto& [it, inserted] = result; binds to its components. You cannot use auto& directly with the result of insert, which is returned by value.
The std::map::insert overload taking one value without a hint returns std::pair<iterator, bool>. On normal return, inserted is true if an element was added and false if the map already had an equivalent key according to its comparator. In either case, it points to the corresponding map element, and it->second reads its stored value. A duplicate does not overwrite that value. false does not report an exception.
Not every overload returns a pair: hinted value insertion returns only an iterator, range insertion returns void, and unhinted node-handle insertion returns insert_return_type. The iterator does not extend the lifetime of the map or the element: further std::map insertions do not invalidate it, but do not use it after the pointed-to element is erased or the map is destroyed.
Examples
#include <iostream>
#include <map>
int main() {
std::map<int, int> m;
const int values[] = {10, 20};
for (int value : values) {
auto [it, inserted] = m.insert(std::map<int, int>::value_type{7, value});
std::cout << std::boolalpha << inserted << ' ' << it->second << '\n';
}
}
Result
true 10 false 10
The first attempt stores `10` at key `7`. The second attempt uses the same key and reports `false`; `it->second` is still `10`, not `20`.
Related lessons
- C++ · Lesson 26 · Intermediate · Version: 2