Search code examples
c++arraysclassconstructorinitializer-list

Initializer list to array


As of now, I have a class Permutation, which has this:

public:
 int elements[N];
 Permutation(std::initializer_list<size_t> data): elements(data) {};

But when I try to compile, I get this:

error: array initializer must be an initializer list

I've googled the hell out of the initialiser lists, though there is nothing that was useful/I could understand. So I do not have the tiniest idea about how to use the initialiser lists.

How do I write this constructor?

UPDATE

I also have this version:

public:
 int elements[N];
 Permutation(std::initializer_list<size_t> data): elements(new int[N]) {
     std::copy(data.begin(), data.end(), elements.begin(), elements.end());
 }

I'm pretty sure it's even more wrong, but if it's fixable, could someone tell me how to do this?


Solution

  • The second approach is close. It needs minor adjustments.

    Permutation(std::initializer_list<int> data) : elements{}
    {
       size_t size = data.size();
       if ( size <= N )
       {
          std::copy(data.begin(), data.end(), std::begin(elements));
       }
       else
       {
          std::copy(data.begin(), data.begin()+N, std::begin(elements));
       }
    }