Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move elements from std::unordered_set to std::vector

Tags:

c++

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?

like image 352
Dmitriano Avatar asked Feb 26 '26 04:02

Dmitriano


1 Answers

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()));
}
like image 129
Dmitriano Avatar answered Feb 27 '26 19:02

Dmitriano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!