给定一个包含MyClass对象的std::vector
。如何使用std::copy
创建另一个仅包含MyClass一个成员数据的向量?我想我必须实现一个自定义的back_inserter
,但到目前为止我还不知道如何做到这一点。
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,你可以自己制作一个函数对象:
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
std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
std::tr1::bind(&MyClass::a, std::tr1::placeholders::_1));
正如@Nawaz在下面评论的那样,BTW执行.reserve()
以防止在复制过程中进行不必要的重新分配。
vec2.reserve(vec1.size());
std::transform(...);
您希望使用std::transform
而不是std::copy
和std::bind
绑定到指向成员变量的指针:
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <functional>
struct foo {
int a;
};
int main() {
const std::vector<foo> f = {{0},{1},{2}};
std::vector<int> out;
out.reserve(f.size());
std::transform(f.begin(), f.end(), std::back_inserter(out),
std::bind(&foo::a, std::placeholders::_1));
// Print to prove it worked:
std::copy(out.begin(), out.end(), std::ostream_iterator<int>(std::cout, "n"));
}
我的例子是C++11,但如果您跳过方便的向量初始化,转而使用boost::bind
,那么在没有C++11的情况下也同样有效。