Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector construction with in place construction of elements

Tags:

c++

c++11

stl

Is it possible to construct a std::vector with an initial size and have it's elements in-place constructed? My stored type is not copyable so this doesn't work because the initial value is constructed as a temporary and copied to the elements:

#include <iostream>
#include <memory>
#include <vector>

struct A
{
    A(int i = 0) : i_ (i) {};
    int i_;
    std::unique_ptr<int> p_; // not copyable
};

int main()
{
    std::vector<A> v (10, 1); // error
}

This is close to what I'm trying to achieve and maybe it isn't so bad, but I'm wondering if there is a cleaner way:

int main()
{
    //std::vector<A> v (10, 1); // error

    std::vector<A> v;
    v.reserve (10);
    for (int i = 0; i < 10; ++i) {
        v.emplace_back (1);
    }
}

I'm limited to c++11 but I'm interested in c++17 solutions as well out of curiosity.

like image 265
atb Avatar asked Jun 03 '19 14:06

atb


2 Answers

You could use std::generate_n:

auto generator = []() {
    return A(1);
};
std::vector<A> v;
v.reserve(10);
std::generate_n(std::back_inserter(v), 10, generator);
like image 134
eerorika Avatar answered Oct 25 '22 10:10

eerorika


Your loop solution looks like the best way.

There's no built-in way to create a vector with N (for N>1) emplace-constructed elements.

like image 43
Lightness Races in Orbit Avatar answered Oct 25 '22 09:10

Lightness Races in Orbit