C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了vs for while循环中的C迭代器行为大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我不明白为什么迭代带有for循环的容器会产生不同的结果,而不是使用while循环迭代它.以下MWE用向量和一组5个整数说明了这一点. @H_403_7@

@H_403_7@

#include <iostream>
#include <vector>
#include <set>
using namespace std;

int main()
{
  vector<int> v;
  set<int> s;

  // add integers 0..5 to vector v and set s
  for (int i = 0; i < 5; i++) {
    v.push_back(i);
    s.insert(i);
  }

  cout << "Iterating through vector with for loop.\n";
  vector<int>::const_iterator itv;
  for (itv = v.begin(); itv != v.end(); itv++) cout << *itv << ' ';
  cout << '\n';

  cout << "Iterating through set with for loop.\n";
  set<int>::const_iterator its;
  for (its = s.begin(); its != s.end(); its++) cout << *its << ' ';
  cout << '\n';

  cout << "Iterating through vector with while loop.\n";
  itv = v.begin();
  while (itv++ != v.end()) cout << *itv << ' ';
  cout << '\n';

  cout << "Iterating through set with while loop.\n";
  its = s.begin();
  while (its++ != s.end()) cout << *its << ' ';
  cout << '\n';
}
@H_403_7@以上产生:

@H_403_7@

Iterating through vector with for loop.
0 1 2 3 4 
Iterating through set with for loop.
0 1 2 3 4 
Iterating through vector with while loop.
1 2 3 4 0 
Iterating through set with while loop.
1 2 3 4 5
@H_403_7@for循环按预期工作,但不是while循环.由于我用作后缀,我不明白为什么while循环的行为与它们一样.另一个谜团是为什么while循环为set s打印5,因为这个数字没有插入s中.

解决方法

使用for循环进行迭代时,只有在计算主体后才增加迭代器.当您使用while循环进行迭代时,您会在检查之后但在循环体之前递增迭代器.在while循环的最后一次迭代中取消引用迭代器会导致未定义的行为.

大佬总结

以上是大佬教程为你收集整理的vs for while循环中的C迭代器行为全部内容,希望文章能够帮你解决vs for while循环中的C迭代器行为所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: