std::copy的自定义插入器
Custom inserter for std::copy
给定一个包含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的情况下也同样有效。
相关文章:
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 为 std::vector 编写自定义插入函数
- 将带有模板的自定义类插入到 std::map 中
- 如何将标准::矢量插入具有自定义排序功能的 std::set 中
- 无法使用带有 std::move 的自定义删除器插入 std::unique_ptr
- 使用自定义比较器C++映射,不插入所有元素
- 当我添加自定义比较器时,无法插入新元素以设置
- 在自定义源和 SmartTee 之间插入筛选器会泄漏 COM 对象
- 自定义char*插入功能多次运行时会产生运行时错误
- 插入同一键时,自定义类的unordered_map不会导致错误
- 正在将自定义传输插入gRPC
- 自定义比较器,将唯一元素插入到c++中的集合中
- std::copy的自定义插入器
- 比较具有替代排序的自定义类型的std::元组(或std::对).是否可以插入自定义的小于/比较函数
- 无法将数字插入到基于 char16_t 的自定义C++ ostream/streambuf
- C++:用于高效插入和检索自定义数据的数据结构
- 在C++中的自定义字符串类中实现插入
- 自定义键出现c++映射插入错误
- 插入自定义类作为映射值
- 如何在std::map中插入自定义对象