开发者

C++ getting the size of an array

I'm new to programming and I was wondering, how to get the size of an array, that is, get the size of how many elements are inside the array. For example if I declare an array of size 10, but only input 3 elements into the array, how would I determine the size of this array? If I don开发者_如何转开发't know how many elements I placed in initially.


If you declare an array, e.g. int array[10], then its size is always 10 * sizeof(int). There is no way to know how many times you've accessed it; you'd need to keep track of that manually.

You should consider using container classes, e.g. std::vector:

std::vector<int> vec;

vec.push_back(5);
vec.push_back(10);
vec.push_back(42);

std::cout << vec.size() << "\n";   // Prints "3"


If you declare an old-style array of 10 elements, e.g. std::string words[10], the size of the array is always 10 strings. Even with the new style (std::array), it would be a fixed size.

You might be looking for a std::vector<>. This doesn't have a fixed size, but does have a .size() method. Therefore, if you add three elements to it, it will have .size()==3


to get the array size (in number of elements) assuming you do not know it in advance use sizeof(a)/sizeof(a[0])

see the below example program. I used C but it should carry over to C++ just fine

#include <stdio.h>

int main(){
    int a[10];
    printf("%d elements\n",sizeof(a)/sizeof(a[0]));
    return 0;
}

//output: 10 elements


There's several possible ways, but they depend on your definition.

If you know there is a value the user won't input (also known as a sentinel value), you can use a function like memset, to set the entire array to that unused value. You would then iterate through the list counting all the variables in the list that don't match that value.

The other way is to build your own array class, which counts whenever the array is modified (you'd have to overload the = and [] functions as appropriate).

You could also build a dynamically linked list, so as the user adds variables, the count can either be determined by walking the list or keeping count.

But, if you're taking the array as the basic array, with no idea as to it's actual starting state, and no idea what to expect from the user (given this is your program, this shouldn't occur), then generally speaking, no, there is known way to know this.


You maintain a counter variable count initialized to 0.

Whenever you are adding to array increment the count by 1. Whenever you are removing from array decrement the count by 1.

anytime count will give you the size of the array.


Suggestion:

int[10] arr;

//init all to null

for (int i =0; i < 10; i++)
     arr[i] = 0;

arr[0]=1;
arr[2]=5;

int sz = 0;

for (int j = 0; j < 10; j++)
    if (arr[j] != 0) sz++;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜