从对象向量中提取元素 [英] Extract elements from a vector of object

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

问题描述

给定一个对象向量,是否有一种优雅的方法来提取其成员?我目前只是在使用for循环,但是如果有一种方法可以很好地使用它.示例:

Given a vector of objects, is there an elegant way to extract its member? I am currently just using a for loop but it would be nice if there is a way to do it. Example:

#include <vector>

struct Object {
  int x;
  float y;
};

int main() {
  std::vector<Object> obj;
  // Fill up obj

  std::vector<int> all_x = obj.x; // Won't work obviously
}

推荐答案

由于 std :: vector (或通常为c ++)不支持协变聚合,因此没有语法上漂亮的方法可以执行此操作你想要的.

As std::vector (or c++ in general) does not support covariant aggregation, there is no syntactically pretty way to do what you want.

如果您确实想使用 obj 元素的 x 成员初始化 all_x ,则可以定义一个新的迭代器类,例如:

If you really want to initialize all_x with x members of obj elements, then you can define a new iterator class, like that:

class getx_iter : public vector<Object>::iterator
{
public:
    getx_iter(const vector<Object>::iterator &iter) : vector<Object>::iterator(iter) {}
    int operator*() { return (*this)->x; }
};

工作代码示例

如果您可以初始化一个空的 vector ,然后填充它,则用labmda填充 std :: transform 是一个更清晰的选择(如@andars所建议).

If you're okay with initializing an empty vector and then filling it, std::transform with a labmda is a clearer option (as @andars suggested).

您还可以通过使用 vector :: reserve() back_inserter :

xs.reserve(foos.size());
std::transform(foos.begin(), foos.end(), back_inserter(xs), [](Foo f){return f.x;});

还请注意,尽管 x Object 的私有成员并且没有吸气剂,但提取它却非常困难.

Also notice that while x is a private member of Object and has no getters, it will be quite hard to extract it.

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

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