如何将向量中对的第一个元素复制到另一个向量? [英] how copy the first elements of pair in vector to another vector?

查看:234
本文介绍了如何将向量中对的第一个元素复制到另一个向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: vector,其元素类型为std :: pair.通过某种算法,我返回了两个迭代器(范围),因此我想拾取该范围内的所有元素并将该对的第一个条目复制到另一个向量

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);
}

使用循环可以做到这一点,但是我想知道是否有一种简单的stl算法可以做到这一点.由于数据大小(如果大于或等于较大)将被重复很多次,因此使用循环非常慢.

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.

推荐答案

如果您正在寻找一种算法来为您完成此操作,则可以使用

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;});

如果不支持C ++ 11,则可以使用函数代替lambda表达式:

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);

这篇关于如何将向量中对的第一个元素复制到另一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆