Reputation: 17
I have two vectors as follows:
std::vector<Foo> v1;
std::vector<Bar> v2;
both Foo
and Bar
possess the .baz
attribute, for example of type int
.
What I would like is to end up with a new vector, combining all .baz
attributes, in order:
std::vector<int> v3;
where v3.size() == v1.size() + v2.size()
Is there a succinct way of achieving this?
Upvotes: 1
Views: 196
Reputation: 217283
With range-v3, it might be:
std::vector<int> v3 = ranges::view::concat(ranges::view::transform(v1, &Foo::baz),
ranges::view::transform(v2, &Bar::baz));
Upvotes: 2
Reputation: 20396
I don't know that you need something more succinct than simply:
int main() {
std::vector<Foo> foos = get_foos();
std::vector<Bar> bars = get_bars();
std::vector<int> vec;
auto merge = [](auto const& arg) {return arg.baz;};
std::transform(foos.begin(), foos.end(), std::back_inserter(vec), merge);
std::transform(bars.begin(), bars.end(), std::back_inserter(vec), merge);
}
Upvotes: 6