我有一个数组变量,举个例子:-
int a[10];
假设我添加了 4 个元素,例如 1,2,3,4
从 a[0]
到 a[3]
.
现在我如何找到最大大小为 10
的数组变量 a
中存在多少元素?
假设用户输入大于或等于零,我获取数组中元素数量的方法:-
#include<iostream>
using namespace std;
#define SIZE 10
int main(){
int *a = (int*)malloc(sizeof(int)*SIZE);
int iCount=0;
int iNumberOfElements,iElements;
cout<<"\nEnter the number of elements to be entered:";
cin>>iNumberOfElements;
cout<<"\nEnter the elements(Please enter elements greater than or equal to zero):\n";
for (int jIndex = 0; jIndex < iNumberOfElements; jIndex++){
cin>>iElements;
while(iElements<0){
cout<<"\nPlease enter the element greater than or equal to Zero.\nRe-enter:\n";
cin>>iElements;
}
a[jIndex] = iElements;
}
for(int iIndex=0;iIndex<SIZE;iIndex++){
if(a[iIndex] >= 0){ //I am checking in this way assuming that user will give input >= 0
iCount++;
}
}
cout<<"\nThe total number of element present in the array is:"<<iCount<<endl;
return 0;
}
最佳答案
您必须自己构建该约定。
例如,您可以将整个数组初始化为某个表示“未使用”的神奇常量,或者您可以通过单独的变量跟踪长度。
不管怎样,框架根本帮不了你,没办法。出于所有意图和目的,该数组有 10 个元素,无论您是否设置它们。
关于c++ - 如何查找数组中存在的元素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6716983/