I can get array length, but I am looking for number of initialized elements

Hello, my intention is to get this:

m_Array[10];
m_Array[0]=1;

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?

1
2
3
4
5
6
7
8
int BaseQueue::Size()
{

  size = sizeof(m_Array) / sizeof(m_Array[0]);
  return size;

}
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    int array[10]{0};
    std::cout << sizeof(array)/sizeof(int) << '\n';
    
    array[3] = 1;
    array[7] = 12;
    
    
    int count{0};
    for(int i = 0; i < sizeof(array)/sizeof(int); i++)
    {
        if ( array[i] != 0)
            count++;
    }
    std::cout << count << '\n';
    
    return 0;
}
If you are allowed you can use std::count.
http://www.cplusplus.com/reference/algorithm/count/

Is a for loop and comparing each element to != zero the best way to determine this?


Maybe not the best, but one of the easiest methods, but only if zero is not a valid value.

By the way since the array is in scope the above code could be simplified to something like (or just std::count as suggested above):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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.



Topic archived. No new replies allowed.