为什么这些基于范围的 for 循环不能正常工作?
Why don't these range based for loops work properly?
输出为 2 3 4 5 2293456 6 10 1355995651 12980632 0
看来我没有正确递增
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int x[5] = {1,2,3,4,5};
vector<int> vec = {2, 4, 6, 8, 10};
for(int i : x) {
cout<<x[i]<<endl;
}
cout<<endl;
for(int i : vec) {
cout<<vec[i]<<endl;
}
}
使用基于范围的 for 循环时,获取的是容器中的值,而不是容器中的索引。因此i
是数组/向量内部的值,而不是索引。
请记住:基于范围的 for 循环适用于没有索引的容器,如 std::list
、std::map
等。它们处理任意迭代器的值范围。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的for循环不能正确获取argv
- 为什么我不能在 while 循环中创建线程?
- 为什么 GCC 不能假设 std::vector::size 在这个循环中不会改变?
- 为什么我不能在 for 循环中出现这样的条件?(C++)
- 对于循环增量器不能用作字符串向量的索引
- 为什么我不能将 size() 函数编写为 while 循环中的条件?
- 为什么for循环中的异步不能提高执行时间
- 为什么我不能在带有 Chrono 的 Windows 上让循环在C++中旋转不到一毫秒?
- C/C++ 不能在 for 循环中运行 for 循环
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- 为什么 for 循环不能定义两个作用域的变量?
- 为什么当数组作为调用方函数中的参数传递时,不能在被调用函数中使用 foreach 循环打印数组的值
- C++ 为什么我不能使用循环:while(fin>>x) 两次
- 为什么 GCC 不能矢量化这个函数和循环
- 代码无限循环不能只打印一次
- 虽然循环不能正常工作,但 C++
- C++ cin.getline() 不能在循环中工作
- 不能使用循环包含转发声明
- 我不知道为什么我不能循环整个代码?当我按 y 时"next customer"