简体   繁体   English

如何使用算法将一个容器中的对象中的成员复制到另一个容器?

[英]How to copy a member in an object in one container to another container using an algorithm?

I have a container of objects and I would like to copy the same member from each object to a container of that member's type. 我有一个对象容器,我想将相同的成员从每个对象复制到该成员类型的容器中。

Ie Something like this: 即是这样的:

struct X { int x; }

std::vector<X> src;
std::vector<int> dst;

...

auto it_dst = dst.begin();
for (auto& element : src) {
  *(it_dst++) = element.x;
}

Of course, using an algorithm and not a for loop. 当然,使用算法而不是for循环。

Seems like a job for transform with a lambda (I consider you haven't allocated your vector): 似乎是用lambda进行transform的工作(我认为您尚未分配向量):

std::transform(src.begin(), src.end(), std::back_inserter(dst),
               [](const auto& v) -> int { return v.x; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将元素从一个容器绑定到另一个容器上的成员函数 - how to bind elements from one container to call member func on another container 将一个STL容器的内容复制到另一个 - Copy content of one STL container to another 使用boost copy将struct的成员作为键映射复制到set容器中 - copy member of struct as key map into set container using boost copy 为容器中的每个对象使用一个参数(绑定)调用成员函数 - Calling a member function with one parameter (bound) for each object in a container 如果STL容器对象的值不是可复制的,则如何将STL容器对象附加/复制到另一个对象,例如的std ::线程 - How to append/copy an STL container object to another object when its value is not copy constructible e.g. std::thread 如何获取成员对象以通知其容器对象? - How do I get a member object to notify its container object? C ++如何在容器类复制构造函数中复制分配器对象 - C++ How to copy the allocator object in a container class copy constructor 复制算法与容器构造函数 - copy algorithm vs. container constructor 如何按值复制到容器类中? - How to copy by value into a container class? 如何复制动态分配的 object(具有一个类的 const 成员) - How to copy a dynamically allocated object (with having one const member of a class)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM