The code below does not move unordered_set elements to vector, but it copies them because unordered_set elements are const.
#include <vector>
#include <unordered_set>
#include <string>
std::unordered_set<std::string> set;
set.insert("a long string number 0000000000000000000000000000001");
set.insert("a long string number 0000000000000000000000000000002");
set.insert("a long string number 0000000000000000000000000000003");
std::vector<std::string> v(std::make_move_iterator(set.begin()), std::make_move_iterator(set.end()));
What is the right way to move the elements?
Even if I remove the elements one by one from unordered_map I call erase method that destroys the element and there is no way to move it, right?
The way to do it, which is possible since C++17, is to use std::unordered_set::extract to extract the node from the map and then move the value out of the node:
std::unordered_set<std::string> set;
std::vector<std::string> v;
v.reserve(set.size());
while (!set.empty())
{
v.push_back(std::move(set.extract(set.begin()).value()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With