Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to convert from vector of pairs to two independent vectors in C++

Tags:

c++

vector

lets say I have a vector of pair<int,int>. Now I want to extract the pair.first and pair.second as independent vectors. I can iterate on the vector and do that but is there a better/faster way?

like image 267
Neal Avatar asked Dec 09 '11 08:12

Neal


People also ask

Are C style arrays faster than vectors?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.


2 Answers

In C++11, if you don't need the old vector anymore, you could perhaps get a tiny bit of extra efficiency from move semantics:

for (auto it = std::make_move_iterator(v.begin()),
         end = std::make_move_iterator(v.end()); it != end; ++it)
{
    v1.push_back(std::move(it->first));
    v2.push_back(std::move(it->second));
}

Other than that, you certainly cannot do better than one loop. You will have to touch every element at least once, so this is as efficient as it gets.

Note that moving can only make a difference if the element types themselves have move semantics that are better than copying. This is not the case for ints, or any PODs. But it can't hurt to write your code generically so that you can take advantage of this in future situations.

If copying/moving is a problem, though, you should consider whether some view adapter for your original vector might be a better approach.

like image 82
Kerrek SB Avatar answered Oct 12 '22 22:10

Kerrek SB


No there is not. The one thing to take care of is to use reserve on the two resulting vectors to prevent unnecessary reallocations.

like image 37
Björn Pollex Avatar answered Oct 13 '22 00:10

Björn Pollex