user1285419
user1285419

Reputation: 2225

how copy the first elements of pair in vector to another vector?

I have a std::vector with element of the type std::pair. With some algorithm, I return two iterators (range) so I would like to pick up all elements within that range and copy the first entry of the pair to another vector

std::vector< pair<double, int> > data;
std::vector<double> data2;
std::vector< pair<double, int> >::iterator it1, it2;

for (;it1!=it2; it1++)
{
  data2.push_back(it1->first);
}

Using a loop will do that but I wonder if there is a straightforward stl algorithm to do that. Since the data size if pretty big and above operation will be repeated for many times, using a loop is pretty slow.

Upvotes: 1

Views: 5271

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

If you are after an algorithm to do this for you, you can use the four parameter overload of std::transform:

#include <algorithm> // for transform
#include <iterator>  // for back_inserted and distance

....
std::vector< pair<double, int> > data;
std::vector<double> data2;
data2.reserve(std::distance(it1, it2));
std::transform(it1, 
               it2, 
               std::back_inserter(data2), 
               [](const std::pair<double, int>& p){return p.first;});

If you don't have C++11 support, you can use a function instead of the lambda expression:

double foo(const std::pair<double, int>& p) { return p.first; }

std::transform(it1, 
               it2, 
               std::back_inserter(data2),
               foo);

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409166

It's because of the operator precedence. The select operator . has higher precedence than the dereference operator *.

So what the compiler thinks you're writing is

*(it1.first)

when you mean

(*it1).first

Upvotes: 0

Related Questions