I have some vector of Foo
s at hand and I want to transform it into a vector of Bar
s, and a const
one. The best way I can think of is:
Bar foo2bar(const Foo& foo);
std::vector<Foo> foos = {...};
const std::vector<Bar> bars = [&foos] {
std::vector<Bar> bars;
bars.reserve(foos.size());
std::transform(foos.cbegin(), foos.cend(),
std::back_inserter(bars),
foo2bar);
return bars;
}();
And I think the return value of the lambda should be elided by most compilers, so this should be close to ideal. The only disadvantage is probably the need to create a lambda, but I don't think it's too much of a problem.
Is there any insidious problem with this approach, and is there any better way (e.g., faster, cleaner)? C++11 is available.
Your simplest solution is to drop the const
requirement altogether. You can still expose a reference-to-const
to other scopes.
Failing that, this should be fine. The lambda body will probably be inlined, "creation" of the lambda is a compile-time process, and the return value will either be moved or elided altogether. Your approach is quite elegant, actually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With