如何仅迭代数组到填充的位置而不遍历到全长
how to iterate an array only up to where it is filled without traversing to full length
我喜欢将这个数组填充到最多 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;
}
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 避免在遍历 IShellItemArray 时出现代码重复
- 从特定键开始遍历地图
- 关于链表遍历和调试的困惑
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 如何仅迭代数组到填充的位置而不遍历到全长