0

In a previous question, I wanted to store some extracted nodes from an std::map into a std::vector<std::map<K, V>::node_type>, using a for loop. Now that I can do that, I'd like to modify the nodes keys before storing them in the vector, and I'm getting a compilation error (not copying the whole error message, it's very long) :

/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.2.0/../../../../include/c++/10.2.0/bits/alloc_traits.h:514:4: error: no matching function for call to 'construct_at'
          std::construct_at(__p, std::forward<_Args>(__args)...);
          ^~~~~~~~~~~~~~~~~

Here is what I'm doing:

  std::vector<decltype(myMap)::node_type> tmp;
  for (auto it = myMap.begin(); it != myMap.end();) {
    if (it->second->needsToBeModified()) {
      auto out = it++;
      auto node = myMap.extract(out);
      node.key() = someNewKey;
      tmp.push_back(node); // The above error message points to this line
    } else
      it++;
  }

If I don't put the node into a variable, the error is gone :

  std::vector<decltype(myMap)::node_type> tmp;
  for (auto it = myMap.begin(); it != myMap.end();) {
    if (it->second->needsToBeModified()) {
      auto out = it++;
      tmp.push_back(myMap.extract(out)); // This is fine
    } else
      it++;
  }

So I guess there is something with the way I manipulate the node but I can't figure it out yet. Could it be possible the problem is with my key which is an std::pair<int16_t, uint32_t>?

aTom
  • 406
  • 6
  • 17

1 Answers1

3

Node handles are not copyable. Thus, you cannot create a copy in the vector.

Node handles are movable though, which is why the other example works.

Moving from a variable can be done using the standard function std::move:

tmp.push_back(std::move(node))
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    "node handle", as a thing, was introduced in C++17 and is described [here](https://en.cppreference.com/w/cpp/container/node_handle) - along with the explanation, given by eerorika, that it is move only. Interesting use cases are: transferring a node between containers (with restrictions on what _kind_ of containers), or changing the key of a node. – davidbak Mar 02 '21 at 18:15