Remembering the contents of C++'s algo functions; lambda expressions.

c-plus-plus functor lambda-expression

I use the std::sort() function a lot for vectors in C++; I need a functor that compares the elements of the vector as the third argument. I knew there was something similar for finding the minimum element of a vector, and there is: std::min_element().

In this case, I wanted to find the element in the vector of OpenCV Point2fs that had the smallest .y member.

#include<algorithm>

...
bool comparePtY(const Point2f& A, const Point2f& B)
{
    return A.y < B.y;
}

... 

vector<Point2f>::iterator minIter1 = std::min_element(points_off_internal_pattern.begin(), points_off_internal_pattern.end(), comparePtY);

cout << "min2 y is " << minIter2->y << endl;

But! While looking through all of the StackOverflow posts, I found something new to me, Lambda expressions, where I could do the same thing in fewer lines ….

vector<Point2f>::iterator minIter2 = std::min_element(points_off_internal_pattern.begin(), points_off_internal_pattern.end(), []  (const Point2f& A, const Point2f& B) {return A.y < B.y;});

My current understanding of Lambda expressions is beginner-level, but some lovely people from Twitter had some recommendations of places to start learning.

Links:

© Amy Tabb 2018 - 2023. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.