std::array

I need to reset all elements to zeros

for example:
not all code shown, so after a loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
..
  std::array<int, 4> did_arr { 0,0,0,0};
      while (j<20000) {
         // at this point did_arr should be reset to all zeros
          for (int x{0} ; x<5; ++x) {
            did = std::rand() % (9 + 1));
            stock_prefix += stock_prefix + "s_dist_0" + std::to_string(did);
            did_arr[x] = did;
             ..
             ..
          }
     }
..
..

Is there a quick way to reset a std::array<int> to zeros?
Last edited on
std::array<int, 4> did_arr {};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <array>


int main()
{
  std::array<int,4> MyArray{};
  
   std::cout << "Array items are\n";
  
  for(auto&& item :  MyArray) {  //auto&& is a forwarding reference, unrelated to this example
      std::cout << item << "\n";
  }
}


Array items are
0
0
0
0


http://en.cppreference.com/w/cpp/language/value_initialization
http://en.cppreference.com/w/cpp/language/aggregate_initialization

cppreference wrote:
If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.


Emphasis added by me :+)

One can use this to partially initialise with some values, the rest are zero:

std::array<int, 4> did_arr {1,2}; // same as {1,2,0,0}

Good Luck !!

Edit:

Seen as though you want to generate some numbers, there is std::generate

http://en.cppreference.com/w/cpp/algorithm/generate

Have a look at the examples :+)

There are better random number generators than std::rand
Last edited on
Topic archived. No new replies allowed.