0

What is the best way to keep track of the number of assigned elements in predefined C++ arrays?

For example, in the following code, one can easily run a loop till it encounters the first 0 in the array:

#include <iostream>
using namespace std;

#define MAX 500

int main() {
  int a[MAX] = {};
  a[0] = 1;
  a[1] = 2;
  a[2] = 3;
  // loop
}

However, if we consider the following definition:

#include <iostream>
using namespace std;

#define MAX 500

int main() {
  int a[MAX] = {};
  a[0] = 1;
  a[1] = 0;
  a[2] = 3;
  // loop
}

Seeking for the first 0 does not work since there is still a value of 3 after the first 0.

My question: How should I initialize the array so that I would have a "stable" rule of counting the number of assigned values?

VIVID
  • 555
  • 6
  • 14
  • 1
    Wrap the array in a structure that also holds a `count` variable. – user4581301 Jan 15 '21 at 18:55
  • Please post the code you are asking about (in this case, the *loops*). – Scott Hunter Jan 15 '21 at 18:56
  • Use a `std::vector` instead. `std::vector a; a.reserve(500);` leaves you with 0 elements, but a capacity of 500 so adding to 500 elements wont cause a reallocation. – NathanOliver Jan 15 '21 at 18:57
  • @NathanOliver I strongly disagree. There might be 1000 and 1 reasons to prefer static arrays to vectors, and general advice of using `vector` instead of array is misplaced. – SergeyA Jan 15 '21 at 18:58

1 Answers1

1

The best way would be to use a structure built specifically to support your use case. The very good one I know of is boost.static_vector.

You can push/pop elements to/from it, you can explicitly set and query it's size, and all the while the storage is allocated statically.

SergeyA
  • 61,605
  • 5
  • 78
  • 137