The number of elements in a static array of a predetermined size

I have an array like this:

int a[100]; 

I fill only the first 4 elements in this array:

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

When I do sizeof(a)/sizeof(a[0]), it returns 100.

Is there a way that I can get the number of elements that I rated the value, and thus filter out the remaining 96 unassigned elements?

thank

+3
source share
7 answers

All elements must be attached to something, so the array always has 100 elements. If you can make sure that all elements are initialized with a special value that means “unassigned” to you (for example, -1), you can execute it as follows:


// fill the array with a special value which means "uninitialized"
const int special_uninitialized = -1;
std::fill(&a[0], &a[100], special_uninitialized);

// set up your values
a[0] = 1;

// count
std::size_t uninitialized_count = std::count(&a[0], &a[100], special_uninitialized);
std::size_t initialized_count = 100 - uninitialized_count;

, , :

  • , std::vector, size() , , ,

  • , ,

  • "" , , std::find, , , . .

std::vector - . :


std::vector<int> vec;

vec.push_back(17);
vec.push_back(23);
vec.push_back(5);

int x = vec[0]; // x will be 17
vec[0] = 40; // set element 0

size_t s = vec.size(); // s will be 3
+3

. .

+8

. , ​​ Vector, , , .

+7

, (, , STL), , @Mitch:

char *Names[100] = {}; // zero init

Names[0] = "hello";
Names[1] = "world";

for (int n = 0; n < 100 && Names[n] != 0; ++n)
    if (!Names[n])
        break;

printf("# of entries: %d", n);

, .

+1

, std::map ? , , std::map::find():

std::map<size_t, int> myMap;
myMap[0] = 1;
// ...
bool contains = myMap.find(0) != myMap.end();
0

"static". , . "" , , , , , . , , "" , .. .

0

, boost:: optional :

boost::optional<int> a[100];

, , :

if (! a[i]) {   // element not set
}
else {  // element not set
}

Using boost: an array instead of a static array might be a good idea.

0
source

Source: https://habr.com/ru/post/1745721/


All Articles