I would like to get the total number of elements in the array (elements that are not zero). Not the maximum capacity of the array which is total of 10.
Can someone clarify how I can get this? Is a for loop and comparing each element to != zero the best way to determine this?
#include <iostream>
int main()
{
int array[10]{0};
array[3] = 1;
array[7] = 12;
int count{0};
for(auto& current : array)
{
if ( current != 0)
count++;
}
std::cout << count << '\n';
return 0;
}
Note: Notice that there is no need for the sizeof operator.
I would consider encapsulating that "raw" array into a class that can keep a count the number of insertions, or perhaps just use std::vector instead and just push the values into the vector.