Reputation: 585
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?
Upvotes: 0
Views: 46
Reputation: 62603
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.
Upvotes: 1