1

outside of a class in main I can initialize a whole array of ints like this:

int array[20] = {0};

It works and its sets all the elements to zero. Within a class, if I try to write the same code in the constructor it doesn't accept it. How can I initialize it with out have to loop through every individual element?

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174

3 Answers3

1

Use fill_n:

class A
{
int array[50];
public:
    A(){
    std::fill_n(array,50,0)
    }
}
vaibhav kumar
  • 885
  • 1
  • 11
  • 13
0

with vector

class Test
{
private:
  std::vector<int> test;

public:
  Test(): test(20) {}


};

or array

class Test
{
private:
  std::array<int, 20> test;

public:
  Test() { }


};
Claudiordgz
  • 3,023
  • 1
  • 21
  • 48
0
#include<iterator>
#include<array>
#include<algorithm>

    class Test
    {
    private:
      int arr[20];
      std::array<int, 20> test;

    public:
      Test() { 
        test.fill(0);  //for std::array
        std::fill(std::begin(arr),std::end(arr),0); //for c-style array
      }
    };

std::array does not initialize its members by default values. So we need to call "fill" method. These code are valid for C++11 standard.

Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48