簡體   English   中英

循環和lambda函數的迭代

[英]Iterative for loop and lambda function

我有以下代碼:

#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;
}

現在,我應該編寫迭代的for循環(內置在cpp for_each循環中),該循環打印出數組的所有元素,其中,我們必須使用自動引用作為迭代變量。

現在,這讓我有些困惑,因為我知道無需任何迭代變量或類似的東西就可以做到:

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

顯然,這不是我要執行的操作,因此,由於我在處理for_each循環時從未發現自己使用迭代變量,因此我想找出我應該如何正確執行此操作,特別是考慮到我必須使用自動引用。 任何幫助表示贊賞!

您可能正在尋找range-for循環

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

如果您正在尋找基於std::for_each的解決方案,則可以執行以下操作。

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

在這里,您有一個要在每次迭代中進行處理的對象的auto&引用(在上述情況下,使用const auto&會很有意義)。

這幾乎與@cdhowie建議的基於范圍的for循環相同 這里唯一需要注意的有趣一點是, std::for_each是為傳遞給STL算法的可調用對象一定不會產生副作用的規則的少數(唯一?)例外之一。 在這種情況下,寫入全局std::cout對象是一個副作用,而std::for_each明確允許這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM