0

Assuming I have a class A and a vector of instances instances

class A {
public:
    int a;
}

std::vector<A> instances;  // Contains several A objects

I now want to create a vector of int from the attribute a of objects in A.

The naive way would be

std::vector attributes;
for (auto& obj: instances) {
    attributes.push_back(obj.a);
}

Is there a way to do it in just one line? Something conceptually close to python's

attributes = [obj.a for obj in instances]
Federico Taschin
  • 2,027
  • 3
  • 15
  • 28
  • [`std::transform`](https://en.cppreference.com/w/cpp/algorithm/transform)? – Alan Birtles May 28 '21 at 09:59
  • `std::vector attributes; std::transform(instances.cbegin(), instances.cend(), std::back_inserter(attributes), [](auto const &e){return e.a;});` – EOF May 28 '21 at 10:00
  • With C++20, `std::ranges::transform(instances, std::back_inserter(attributes), &A::a)` using the projection argument, should work and be much more succinct than the old way. – underscore_d May 28 '21 at 10:03

1 Answers1

3

Use std::transform.

std::vector<...> attributes;
attributes.reserve(instances.size());
std::transform(instances.begin(), instances.end(), std::back_inserter(attributes),
               [](auto&& obj) { return obj.a; });
songyuanyao
  • 169,198
  • 16
  • 310
  • 405