How to create a constructor initialized with a list?

How can I initialize a constructor using a list with n elements?

X x = {4, 5, 6, ...};
+3
source share
3 answers

For a list with n elements, you need to use std :: initializer_list.

Initializer_list objects are automatically created as if an array of elements of type T, each of the elements into which is initialized by copying to the corresponding element in the array, using any necessary non-narrowing implicit conversions.

The following is an example:

#include <iostream>
#include <initializer_list>
#include <vector>

template<class T>
class X {
  long unsigned int size;
  std::vector<T> _elem;
public:
  X(std::initializer_list<T> l): size{l.size()} {
    for(auto x: l)
      _elem.push_back(x);
  }

  void print() {
    for(auto x: _elem)
      std::cout << x << " ";
  }
};

int main(int argc, char **argv) {
  X<int> x = {4, 5, 10 ,8 ,6};
  x.print();
  return 0;
}

More information about std :: initializer_list: http://www.cplusplus.com/reference/initializer_list/initializer_list/

+7

, , initializer_list?

#include <initializer_list>

class X {
public:
  X(std::initializer_list<int> ilist);
};
+2

You can define the so-called initializer constructor constructor and use class iterators std::initializer_listto access the items in the list.

In accordance with the C ++ standard

initializer list constructor, if its first parameter is of type std :: initializer_list or a link, possibly with the qualification cv std :: initializer_list for some type E, and either no other parameters or all other parameters have default arguments

for instance

#include <iostream>
#include <vector>
#include <initializer_list>

class A
{
public:
   A() = default;
   A( std::initializer_list<int> l ) : v( l ) {}
   std::vector<int> v;
};

int main() 
{
    A a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    for ( int x : a.v ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}
+2
source

All Articles