自定义插入器,用于std :: copy [英] Custom inserter for std::copy

查看:54
本文介绍了自定义插入器,用于std :: copy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个 std :: vector ,其中保存MyClass对象。如何使用 std :: copy 创建另一个仅保留MyClass成员数据的向量?我想我必须实现一个自定义的 back_inserter ,但到目前为止我还不知道该怎么做。

Given a std::vector which holds objects of MyClass. How can I create another vector which holds just data of one member of MyClass using std::copy? I guess I would have to implement a custom back_inserter but I could not figure out how to do this so far.

struct MyClass {
   int a;
}

std::vector<MyClass> vec1;

// I could copy that to another vector of type MyClass using std::copy.
std::copy(vec1.begin(), vec1.end(); std::back_inserter(someOtherVec)

// However I want just the data of the member a, how can I do that using std::copy?
std::vector<int> vec2;


推荐答案

使用 std: :transform

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               [](const MyClass& cls) { return cls.a; });

(如果您不能使用C ++ 11,则可以自己创建函数对象:

(If you can't use C++11, you could make a function object yourself:

struct AGetter { int operator()(const MyClass& cls) const { return cls.a; } };

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), AGetter());

或如果可以使用TR1,请使用 std :: tr1 :: bind

or use std::tr1::bind if you can use TR1:

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               std::tr1::bind(&MyClass::a, std::tr1::placeholders::_1));






BTW,正如@Nawaz在下面评论的那样, .reserve()以防止在复制期间不必要的重新分配。


BTW, as @Nawaz commented below, do a .reserve() to prevent unnecessary reallocation during the copy.

vec2.reserve(vec1.size());
std::transform(...);

这篇关于自定义插入器,用于std :: copy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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