Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Splicing for maps and sets

Use case

Move entries between symbol tables without copying.

Explanation

extract removes and returns a node handle for single entries. merge transfers all nodes from one container to another. Both avoid copying data.

Code

#include <cstdint>
#include <iostream>
#include <map>

int main() {
  std::map<uint64_t, const char *> text = {{0x1000, "_main"},
                                           {0x1100, "_helper"}};

  std::map<uint64_t, const char *> data = {{0x2000, "_global"},
                                           {0x2100, "_buffer"}};

  data.insert(text.extract(0x1100));

  data.merge(text);

  std::cout << "text size: " << text.size() << "\n";
  std::cout << "data size: " << data.size() << "\n";

  for (const auto &[addr, name] : data) {
    std::cout << "0x" << std::hex << addr << ": " << name << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/splicing-for-maps-and-sets
text size: 0
data size: 4
0x1000: _main
0x1100: _helper
0x2000: _global
0x2100: _buffer