Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently moving contents of std::unordered_set to std::vector

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));
like image 339
nalyd88 Avatar asked Feb 28 '17 22:02

nalyd88


People also ask

Which one is faster stack or vector?

vector will outperform list for almost every use case.

What is the fastest container in C++?

Overall, for insertions, the vector and deque are the fastest for small types and the list is the fastest for the very large types.

Is unordered set faster than vector?

vector is fast and is the best choice 99% of the time. Unless, of course, if correctness is more important than performance, then use unordered_set and switch to vector only if performance problems arise from the use of unordered_set .

Which is faster unordered set or set?

unordered_set time was better than set (15494846) : 93<155.


1 Answers

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 doubles, this wouldn't matter.

like image 65
Barry Avatar answered Oct 21 '22 21:10

Barry