C++ 将对象向量中的元素复制到具有此元素的向量中 [英] C++ Copy elements from an object vector into a vector with this element

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

问题描述

我想将 a 值从 foos 向量复制到另一个只有 int 值的向量中.最快的方法是什么?

I want to copy the a values from the foos vector into another vector with just the int value. What's the fastest way to do this?

#include <vector>

struct Foo {
   int a;
};

int main() {
   std::vector<Foo> foos;
   for(int i = 0; i < 100; i++)
      foos[i].a = i;

   std::vector<int> somenumbers;
   //Fastest way to copy the ints from the struct into the somenumbers vector?  

   return 0;
}

推荐答案

什么是最快?只是循环,或算法,或其他东西.例如:

What do you mean fastest? Just loop, or algorithm, or something else. For example:

std::transform
(
    foos.begin(), foos.end(), std::back_inserter(somenumbers),
    [](const Foo& v) { return v.a; }
);

此外,由于您知道向量的大小 - 您应该调用reserve.

Also, since you know size of vector - you should callreserve.

这篇关于C++ 将对象向量中的元素复制到具有此元素的向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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