Reputation: 5138
In my code I have a std::unordered_set
and I need to move the data into a std::vector
. I'm using the std::unordered_set
while getting the data to ensure only unique values are stored prior to converting to a std::vector
. My question is how do I move the contents to the std::vector
the most efficiently? I don't need the std::unordered_set
after the data is moved. I currently have the following:
std::copy(set.begin(), set.end(), std::back_inserter(vector));
Upvotes: 24
Views: 38082
Reputation: 1
I'm using C++ 17 and this approach worked fine for me:
vector<string> vec(set.begin(), set.end());
Please reference to Convert Set To Vector in C++ to more examples.
Upvotes: 0
Reputation: 303087
Before C++17, the best you can do is:
vector.insert(vector.end(), set.begin(), set.end());
The set
's elements are const
, so you can't move from them - moving is just copying.
After C++17, we get extract()
:
vector.reserve(set.size());
for (auto it = set.begin(); it != set.end(); ) {
vector.push_back(std::move(set.extract(it++).value()));
}
Although given your comment that your data is double
s, this wouldn't matter.
Upvotes: 39