Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to initialize vector member from list of values

Tags:

c++

c++11

I am trying to initialize a vector member variable with an array of integers:

#include <vector>
#include <iostream>

struct A
{
    A(int arr[]) : mvec(arr)
    { }
    std::vector<int> mvec;
};

int main()
{
    A s({1,2,3});
}

Compilation gives me error :

$ c++ -std=c++11 try59.cpp

try59.cpp:15:12: note: candidates are:
try59.cpp:6:1: note: A::A(int*)
 A(int arr[]) : mvec(arr)

How can I initialize my vector using an array of integers?

like image 387
Programmer Avatar asked Jan 01 '23 15:01

Programmer


2 Answers

I would just use a std::initializer_list since that's what you're already passing

A(std::initializer_list<int> arr) : mvec(arr)
{

}
like image 159
Cory Kramer Avatar answered Jan 26 '23 06:01

Cory Kramer


If for some reason you really want to initialize a vector using a C-style array and not std::initializer_list, you can do it using additional level of indirection:

struct A {
    template<std::size_t n>
    A(const int (&arr)[n]) :
        A(arr, std::make_index_sequence<n>{})
    { }

    template<std::size_t... is>
    A(const int (&arr)[sizeof...(is)], std::index_sequence<is...>) :
        mvec{arr[is]...}
    { }

    std::vector<int> mvec;
};

A a({1, 2, 3});

Edit. As François Andrieux pointed in the comment, std::vector can be initialized using a pair of iterators, so the constructor simplifies to:

template<std::size_t n>
A(const int (&arr)[n]) : mvec(arr, arr + n)
{ }

But if you were initializing, e.g., std::array instead of std::vector, index_sequence trick seems to be unavoidable.

like image 45
Evg Avatar answered Jan 26 '23 06:01

Evg