applying the std::find function to a vector of structures vector<myStruct) vec

I have asked a related question before, and it was resolved successfully. In the past, when I wanted to use std::max_element in order to find the maximum element (or even sort by using std::sort) of a vector of structures according to one of the members of the structure, all I had to do was to insert a specially designed comparison function as the third argument of the function std::max::element. But the latter comparison function naturally accepts two arguments internally.

For instance, here is a test program that successfully finds the maximum according to just one member of the structure:

-------------------------------------------------------
However, I now need to search and find an element of vector<myStruct> according to just one member of myStruct, instead of finding the maximum or sorting as before. This presents a problem because the function std::find does not accept such a comparison function as its third argument.

std::find_if is appropriate here. One solution is to create a function object with the value that you want to compare against as a member variable. Another option, more in line with what you already have, is to make use of the x variable by bringing it into the scope of the lambda function, e.g.,

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

std::find_if is appropriate here. One solution is to create a function object with the value that you want to compare against as a member variable. Another option, more in line with what you already have, is to make use of the x variable by bringing it into the scope of the lambda function, e.g.,

This is the perfect solution, and I can see that I will be using this syntax for many years in the future! The trouble is that I don't yet understand the lambda functions. I need to do more homework from C++ books.

Many thanks LaserLight: you have answered my question with the speed of light.

You're welcome. I notice that this site has a guide to Lambda Functions in C++11 which may be more accurate than the description that I have used.

Originally Posted by Bjarne Stroustrup (2000-10-14)

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.