简体   繁体   English

循环和lambda函数的迭代

[英]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. 现在,我应该编写迭代的for循环(内置在cpp for_each循环中),该循环打印出数组的所有元素,其中,我们必须使用自动引用作为迭代变量。

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. 显然,这不是我要执行的操作,因此,由于我在处理for_each循环时从未发现自己使用迭代变量,因此我想找出我应该如何正确执行此操作,特别是考虑到我必须使用自动引用。 Any help appreciated! 任何帮助表示赞赏!

You're probably looking for the range-for loop : 您可能正在寻找range-for循环

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::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& ). 在这里,您有一个要在每次迭代中进行处理的对象的auto&引用(在上述情况下,使用const auto&会很有意义)。

This is almost identical to the range-based for loop suggested by @cdhowie . 这几乎与@cdhowie建议的基于范围的for循环相同 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. 这里唯一需要注意的有趣一点是, std::for_each是为传递给STL算法的可调用对象一定不会产生副作用的规则的少数(唯一?)例外之一。 In this case, writing to the global std::cout object is a side effect, and std::for_each explicitly allows that. 在这种情况下,写入全局std::cout对象是一个副作用,而std::for_each明确允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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