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?
I would just use a std::initializer_list
since that's what you're already passing
A(std::initializer_list<int> arr) : mvec(arr)
{
}
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.
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