c++ - number of elements in a static array of a predefined size -


I have an array like this:

  int a [100];  

I'm just filling out the first 4 elements in this array:

  a [0] = 1; A [1] = 2; A [2] = 3; A [3] = 4;  

When I it returns 100.

Is there any way to get the number of elements on which I have collected a value and thus filter the remaining 96 designated elements?

Thanks

All elements should be assigned something, thus in the array There are always 100 elements if you can ensure that all elements are started for a particular value, which means "unassigned" (example -1), then you can work it like this:

  A special value, which means "raw" const special adjectives = 1; Std :: fill (and one [0], and one [100], special_ununized); // Set your values ​​[0] = 1; // count std :: size_t uninitialized_count = std :: count (and one [0], and one [100], special_ununized); Std :: size_t initialized_count = 100 - uninitialized_count;  

If you just want to know how many elements are in an array, then you have these options:

  1. Do not use an array Use std :: vector , which has a size () function, and usually a better option than the original array

  2. <

  3. Use the special "Assigned" value as described above, and std :: find to find the first one, and this address It turns out that how many Are Ujud. This is a pretty ugly solution.

For starters, std :: vector is a better option, you can use it like this:

  std :: vector & lt; Int & gt; Vec; Vec.push_back (17); Vec.push_back (23); Vec.push_back (5); Int x = vec [0]; // x 17 would be vec [0] = 40; // set element 0 size_t s = vec.size (); // will be 3  

Comments