Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform into a const vector

Tags:

c++

c++11

I have some vector of Foos at hand and I want to transform it into a vector of Bars, 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.

like image 998
Zizheng Tai Avatar asked Mar 12 '23 18:03

Zizheng Tai


1 Answers

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.

like image 65
Lightness Races in Orbit Avatar answered Mar 19 '23 00:03

Lightness Races in Orbit