【发布时间】:2014-12-09 14:51:24
【问题描述】:
问题:检查向量中的连续元素if v[i] < v[i+1] + 1
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>v{1,2,3,4,5,6,7,8,9,10};
for(auto &i: v)
{
cout << (i+1) << endl;
}
//SIMILAR TO THIS FOR LOOP
for(int i = 0; i < v.size() - 1;i++)
{
if(v[i] < v[i+1] + 1){cout << "ok" << endl;}
}
return 0;
}
问题:
- 通过使用
for(auto &i: v)如何使用索引来比较两个连续的元素? - 我不想在源代码中使用第二个 for 循环,因为矢量 size 可能会改变。通过使用 auto,我不必担心元素是否被删除并且矢量是否会调整大小,对吗?
【问题讨论】:
-
你今天或多或少不能。也许将来我们会得到类似python的
zip。 -
你不能。
i不是迭代器。使用带有迭代器或索引的常规for循环。 -
有些事情你不能用基于范围的 for 循环来做。在这种情况下使用迭代器
-
您的
for循环具有未定义的行为,当i是最后一个索引时,您访问v[i+1] -
//////////////////del