Node Handle

During a random documentation check on google noticed new member function overloads for some containers taking what happens to be a new standard type from C++17 called a Node Handle.

"Its purpose is to be able to move items from one map to another without invoking any overhead for copying or moving keys or data."

I knew associative containers like std::set/sed::map are node based container.

But I am not getting how to use it to move an item from one container to another?
Could anyone please give me a simple example?
"Its purpose is to be able to move items from one map to another without invoking any overhead for copying or moving keys or data."

Such handles can even outlive the container.

You can find examples in the paper:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0083r2.pdf

Also see
http://en.cppreference.com/w/cpp/container/node_handle
Last edited on
Here's a simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <map>

int main()
{
    std::map< int, std::string > all_numbers
    { {0,"zero"}, {1,"one"}, {2,"two"}, {3,"three"}, {4,"four"}, {5,"five"}, {6,"six"}, {7,"seven"} } ;
    std::cout << "all numbers (map, before move): " ;
    for( const auto& pair : all_numbers ) std::cout << "{ " << pair.first << ", " << pair.second << "} " ;
    std::cout << '\n' ;

    std::multimap< int, std::string > odd_numbers { {1,"one"}, {5,"five"}, {9,"nine"} } ;

    // move odd numbered items from map all_numbers into multimap odd_numbers
    // (we can move nodes from a map to a multimap if the value_type and allocator_type of both are identical;
    // the node handles are compatible.). inserting an empty node handle does nothing.
    // note that node handles can't be copied; they must be moved 
    for( int key = 1 ; key < 1000 ; key += 2 ) odd_numbers.insert( all_numbers.extract(key) ) ;

    std::cout << "even numbers (map, sfter move): " ;
    for( const auto& pair : all_numbers ) std::cout << "{ " << pair.first << ", " << pair.second << "} " ;
    std::cout << '\n' ;

    std::cout << "        odd numbers (multimap): " ;
    for( const auto& pair : odd_numbers ) std::cout << "{ " << pair.first << ", " << pair.second << "} " ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/f935388cd879e216
Last edited on
Thanks mbozzi for your helpful reply.
Thank you very much JLBorges, The example is really very simple to understand Node handle and extract() function.

:)
Topic archived. No new replies allowed.