简体   繁体   中英

Initialize std::vector of std::unique_ptr with lambdas

Is it possible to initialize an std::vector in a single line using lambda functions?

I am using the following aliases:

using UI = std::unique_ptr<int>;
using VUI = std::vector<UI>;

So far, I am able to do the following:

UI init[] = { UI(new int(0)), UI(new int(0)), UI(new int(0)) };
VUI vec { std::make_move_iterator(std::begin(init)), std::make_move_iterator(std::end(init)) };

VUI vec;
for (unsigned i=0; i<3; ++i)
    vec.emplace_back(UI(new int(0)));

I would like to do something like this but in a single line, preferably using lambdas.

Something like this?

int main()
{
    using UI = std::unique_ptr<int>;
    using VUI = std::vector<UI>;

    VUI vec{ []()
             {
                 VUI v;
                 for (int i=0; i<3; ++i)
                     v.emplace_back(new int(0));
                 return v;
             }()};
}

But why?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM