如何找到数组中存在的元素数量? [英] How to find number of elements present in an array?

查看:198
本文介绍了如何找到数组中存在的元素数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组变量,例如: -

I have an array variable, say for an example:-

int a[10];

假设我添加了4个元素, 1,2,3,4 a [0] a [3] 开始。
现在我如何找到数组变量 a 中存在多少元素,其最大大小为 10

And suppose i have added 4 elements say 1,2,3,4 starting from a[0] till a[3]. Now how do i find that how much element is present in the array variable a whose max size is 10?

我的方法是获取数组中存在的元素数,假设用户将输入大于或等于零: / em>

#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;
}


推荐答案

例如,您可以将整个数组初始化为一个表示未使用的魔术常量,或者您可以通过单独的变量跟踪长度。

For instance, you could initialize the whole array to some magic constant that signals "not in use", or you could track the length through a separate variable.

无论如何,框架根本不会帮助你,没有办法。对于所有意图和目的,数组有10个元素,无论你是否设置。

Either way, the framework will not help you at all, there is no way. For all intents and purposes, the array has 10 elements, whether you set them or not.

这篇关于如何找到数组中存在的元素数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆