std::map<Key,T,Compare,Allocator>::extract
node_type extract( const_iterator position ); |
(1) | (since C++17) |
node_type extract( const Key& k ); |
(2) | (since C++17) |
template< class K > node_type extract( K&& x ); |
(3) | (since C++23) |
position
and returns a
node handle that owns it.
k
, unlinks the node that contains that element from the container and returns a
node handle that owns it. Otherwise, returns an empty node handle.
Compare::is_transparent
is valid and denotes a type, and neither
iterator
nor
const_iterator
is implicitly convertible from
K
. It allows calling this function without constructing an instance of
Key
.
In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed (rebalancing may occur, as with erase()
).
Extracting a node invalidates only the iterators to the extracted element. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container.
Parameters
position | - | a valid iterator into this container |
k | - | a key to identify the node to be extracted |
x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted |
Return value
A node handle that owns the extracted element, or empty node handle in case the element is not found in (2,3).
Exceptions
Compare
object.
Complexity
a.size()
)
Notes
extract is the only way to change a key of a map element without reallocation:
map<int, string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}}; auto nh = m.extract(2); nh.key() = 4; m.insert(move(nh)); // m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}}
Feature testing macro: __cpp_lib_associative_heterogeneous_erasure
(for overload (3)).
Example
#include <algorithm> #include <iostream> #include <map> int main() { std::map<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; std::cout << "Start:"; std::for_each(cont.begin(), cont.end(), print); std::cout << '\n'; // Extract node handle and change key auto nh = cont.extract(1); nh.key() = 4; std::cout << "After extract and before insert:"; std::for_each(cont.begin(), cont.end(), print); std::cout << '\n'; // Insert node handle back cont.insert(move(nh)); std::cout << "End:"; std::for_each(cont.begin(), cont.end(), print); std::cout << '\n'; }
Output:
Start: 1(a) 2(b) 3(c) After extract and before insert: 2(b) 3(c) End: 2(b) 3(c) 4(a)
See also
(C++17)
|
splices nodes from another container (public member function) |
inserts elements or nodes (since C++17) (public member function) |
|
erases elements (public member function) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/container/map/extract