gpt4 book ai didi

c++ - 使用 Iterator 比较 Vector 中的连续元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:51 24 4
gpt4 key购买 nike

问题:检查 vector 中的连续元素 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 循环,因为 vector size 可能会改变。通过使用 auto,我不必担心元素是否被删除并且 vector 大小被调整,对吗?

最佳答案

for(int i = 0; j < v.size();i++)
{
if(v[i] < v[i+1] + 1){cout << "ok" << endl;}
}

这个循环有未定义的行为,你访问v[i+1]什么时候i是最后一个索引。您需要条件为 i+1 < v.size()

  • by using for(auto &i: v)how can I use the index in order to compare two successive elements?

因为 std::vector保证有连续存储使用基于范围的 for 时可以访问下一个元素循环:

for (auto& i : v)
if (i < *(&i+1) + 1) {cout << "ok" << endl;}

然而,这与您的 for 存在相同的问题循环,它将访问 vector 的末尾之后,在这种情况下无法停止它,因为您不能使用基于范围的 for如果要在范围结束之前停止迭代,请循环。你需要做:

size_t count = 0;
for (auto& i : v)
if (++count < v.size() && i < *(&i+1) + 1) {cout << "ok" << endl;}

此时您还不如使用普通的 for循环,更简单明了。

  • I don't want to use the second for loop in the source code because vector size might change. By using auto i don't have to worry if elements are erased and the vector is resized is that right?

不!您不得使用基于范围的 for循环任何时髦的东西,比如迭代正在修改的 vector ,它只是从固定范围的第一个元素到最后一个元素,没什么特别的。

如果您尝试在 vector 被修改时使用它,那么它要么离开 vector 的末尾,要么如果 vector 增长并重新分配,那么基于范围的循环在幕后使用的迭代器将失效.

如果您需要做一些比依次访问每个元素更复杂的事情,那么不要使用基于范围的 for循环

关于c++ - 使用 Iterator 比较 Vector 中的连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27381812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com