关于C ++ 11循环和迭代器范围 [英] About c++11 range for loops and iterators
本文介绍了关于C ++ 11循环和迭代器范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
导致循环的 c ++ 11
范围引起什么:
What does the c++11
range for loops do that cause this:
std::list<Point> item;
....
//fill the list somewhere else
....
for(Point p : item) {
p.lowerY();
}
只工作一次(即 lowerY( )
只会执行一次,但是下次到达此循环时,它什么也不会做),但是:
To work only one time (that is lowerY()
does what it's supposed to do only once but the next time this loop is reached, it doesn't do anything), but this:
list<Point>::iterator it;
for (it = item.begin();it != item.end();++it) {
it->lowerY();
}
每次都能完美运行。有什么区别?
Works perfectly every time. What's the difference?
推荐答案
在您以前的代码中,该行
In your former code, the line
for(Point p : item) {
创建以下项的副本每次您访问下一个项目时的关键点。为了确保您对方法LowerY()的调用有效,您需要将其重新定义为
creates copies of the point every time you access the next item. To make sure that your calling of method lowerY() works, you need to redefine it as
for(Point & p : item) {
这篇关于关于C ++ 11循环和迭代器范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文