简体   繁体   中英

About c++11 range for loops and iterators

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();
}

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) {

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM