vs for while循环中的C迭代器行为
发布时间:2020-12-16 06:45:59 所属栏目:百科 来源:网络整理
导读:我不明白为什么迭代带有for循环的容器会产生不同的结果,而不是使用while循环迭代它.以下MWE用向量和一组5个整数说明了这一点. #include iostream#include vector#include setusing namespace std;int main(){ vectorint v; setint s; // add integers 0..5 t
我不明白为什么迭代带有for循环的容器会产生不同的结果,而不是使用while循环迭代它.以下MWE用向量和一组5个整数说明了这一点.
#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'; } 以上产生: 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 for循环按预期工作,但不是while循环.由于我用作后缀,我不明白为什么while循环的行为与它们一样.另一个谜团是为什么while循环为set s打印5,因为这个数字没有插入s中. 解决方法
使用for循环进行迭代时,只有在计算主体后才增加迭代器.当您使用while循环进行迭代时,您会在检查之后但在循环体之前递增迭代器.在while循环的最后一次迭代中取消引用迭代器会导致未定义的行为.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |