简体   繁体   中英

Iterative for loop and lambda function

I have the following code:

#include <iostream>
#include <algorithm>

struct Point
{
    int x, y;
    Point(int x, int y): x(x), y(y) {}
};

int main()
{
    Point arr[] = {
        Point(4,2), Point(0,3), Point(1,2)
                    };

    std::sort(arr, arr+sizeof(arr)/sizeof(Point), [](Point a, Point b){return a.x<b.x;});

    return 0;
}

Now, i am supposed to write iterative for loop (built in cpp for_each loop) which prints out all of the elements of the array, where, as a iteration variable we must use auto reference.

Now, this confuses me a bit, since i know this can be done without any iteration variables or something, like this:

std::for_each(arr,arr + sizeof(arr)/sizeof(Point), [](Point a){cout<<a.x<<a.y<<std::endl;}

Obviously, this is not what i am asked to do, so, since i never found myself using iteration variables when dealing with for_each loop, i'd like to find out how am i supposed to do that properly, especially considering the fact that i have to use auto reference. Any help appreciated!

You're probably looking for the range-for loop :

for (auto & i : arr) {
    std::cout << i.x << ',' << i.y << '\n';
}

If you're looking for a solution based on std::for_each , you can do the following.

std::for_each(std::begin(arr), std::end(arr),
    [](auto& p){ cout << p.x << p.y << "\n"; });
    // ^^^^^ auto reference

Here, you have an auto& reference for the object that you intend to do something with in each iteration (in the case above, it would make sense to use const auto& ).

This is almost identical to the range-based for loop suggested by @cdhowie . The only interesting point to note here is that std::for_each is one of the few (the only?) exception to the rule that callables passed to STL algorithms must not have side effects. In this case, writing to the global std::cout object is a side effect, and std::for_each explicitly allows that.

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