如何仅迭代数组到填充的位置而不遍历到全长

how to iterate an array only up to where it is filled without traversing to full length

本文关键字:遍历 位置 何仅 迭代 数组 填充      更新时间:2023-10-16

我喜欢将这个数组填充到最多 a[4],并且只想遍历最多第 4 个位置而不是 enire 长度。

 int main()
{
    int a[10],i,j=0;
    cout<<"nEnter 4 number :";
    for(i=0;i<4;i++)
    {
        cin>>a[i];
    }
    while(a[j]!='')
    {
        cout<<a[j];
        j++;
    }
}

此代码打印 11 个数字

如果可以使用特殊值(例如零)来指示末尾之后的项目,就像 C 字符串中使用 '' 的方式一样,则可以在将a初始化为所有零后使用您的方法:

int a[10] = {0};
...
while (a[j]) {
    cout << a[j++];
}

这种方法的缺点是结束标记在输入中变得无效。换句话说,如果最终用户在四个输入中输入零,则在打印少于四个项目后,打印将停止。

这就是为什么这两种方法更常见的原因:

  • 使用动态容器,例如 std::vector<int> - 此方法仅在 C++
  • 将项目数存储在单独的变量中 - 如果必须使用"原始"数组,则此方法是最常见的。

答案是:你不能。 int数组没有像 C 样式字符串终止那样的东西。

数组

具有固定大小,数组无法判断您写入了多少元素。因此,如果你想为此使用数组,你必须使用广告代码来计算你编写了多少元素,即使用额外的变量进行计数。

喜欢:

int a[10],i,j=0;
int valid_elements = 0;
cout<<"nEnter 4 number :";
for(i=0;i<4;i++)
{
    cin>>a[i];
    ++valid_elements;
}
for(i=0;i<valid_elements;i++)
{
    cout<<a[i];
}

但是,这通常不是一个好方法。

一个更好的方法是向量,因为向量中的元素数量是动态的。您可以执行以下操作:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> a;
    int i, j;
    cout<<"nEnter 4 number :";
    for(i=0;i<4;i++)
    {
        cin>>j;
        a.push_back(j);
    }
    for (int x : a) // Range based for loop automatic iterates all elements in the vector
    {
        cout<<x;
    }
    return 0;
}