Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何只迭代数组到填充的位置,而不遍历到整个长度_C++_Arrays_For Loop - Fatal编程技术网

C++ 如何只迭代数组到填充的位置,而不遍历到整个长度

C++ 如何只迭代数组到填充的位置,而不遍历到整个长度,c++,arrays,for-loop,C++,Arrays,For Loop,我喜欢将这个数组填充到[4],并且只希望遍历到第4个位置,而不是enire长度 intmain() { int a[10],i,j=0; cout如果您可以使用特殊值(如零)来指示结束后的项目,就像C字符串中使用'\0'的方式一样,您可以在将a初始化为全零后使用您的方法: int a[10] = {0}; ... while (a[j]) { cout << a[j++]; } inta[10]={0}; ... while(a[j]){ 答案是:你不能。int数组没有C风

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

intmain()
{
int a[10],i,j=0;

cout如果您可以使用特殊值(如零)来指示结束后的项目,就像C字符串中使用
'\0'
的方式一样,您可以在将
a
初始化为全零后使用您的方法:

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

答案是:你不能。
int
数组没有C风格的字符串终止

数组的大小是固定的,数组无法告诉您写入了多少个元素。因此,如果要使用数组进行此操作,则必须编写ad代码来计算您写入了多少个元素,即使用额外的变量进行计数

比如:

inta[10],i,j=0;
int有效_元素=0;

coutPrefer
std::vector
std::array
到C样式数组。向上的
a[4]
中的值未初始化且不确定。您不能这样做。您从未将数组初始化为零,因此它包含随机数。终止值
“\0
不需要您添加,它不会出现在那里。
int a[10] = {0};
...
while (a[j]) {
    cout << a[j++];
}
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;
}