How to initialize an array of two-dimensional boolean arrays / char with a fill function in C ++?

I want to initialize a two-dimensional array of type bool with a true value.

bool a[5][5] = {true}; //Well this won't work

fill(a,a+sizeof(a),true); // This throws an error too. 

how to do it?

+4
source share
1 answer
bool a[5][5] {{true, true, true, true, true},
              {true, true, true, true, true},
              {true, true, true, true, true},
              {true, true, true, true, true},
              {true, true, true, true, true}};

Correct, but fragile - if you resize the array without changing the part, the true, true, true...added part of the array will be initialized with false.

Better to just use for a loop:

bool a[5][5];
for (auto& r: a)
    for (bool& b: r)
        b = true;

or use std::vector:

std::vector<std::vector<bool> > a(5, {true, true, true, true, true});
+3
source

Source: https://habr.com/ru/post/1599717/


All Articles