Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Akiiino Avatar asked May 27 '26 10:05

Akiiino


1 Answers

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));
   }
}
like image 69
R Sahu Avatar answered May 30 '26 07:05

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!