[RESOLVED] Using Lambdas to search a std::vector for an object ... (Help)
I'm trying to understand Lambda expressions.
And I guess it's true that teaching an old dog new tricks is tricky.
I've inserted a code sample below; what I'm looking for is a lambda expression/statement that searches myVector for an element in
the vector that has an integer (endpoint) with a specified value.
I'd like the code to simply print out the position of the element in the vector where the endpoints' value matches the expression.
Code:
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
using namespace std;
/*
*
*/
int
main (int argc, char** argv)
{
typedef struct mystruct
{
int endpoint;
mystruct (int a)
{
endpoint = a;
}
} MyStruct;
std::vector<std::unique_ptr < MyStruct>> myVector;
for ( int i = 0; i < 5; i++ )
myVector.emplace_back(new MyStruct (i*i));
// Lambda expression here to search myVector for instance where endpoint = 9;
// and print the position of that element in the vector.
// Output should obviously be 3;
return 0;
}
Re: Using Lambdas to search a std::vector for an object ... (Help)
Perhaps you could consider something like this, compiling with respect to C++14 or later:
Code:
#include <algorithm>
#include <iostream>
#include <memory>
#include <vector>
struct MyStruct
{
int endpoint;
explicit MyStruct(int a) : endpoint(a) {}
};
int main()
{
std::vector<std::unique_ptr<MyStruct>> myVector;
for (int i = 0; i < 5; ++i)
{
myVector.emplace_back(new MyStruct(i * i));
}
// Lambda expression here to search myVector for instance where endpoint = 9;
// and print the position of that element in the vector.
// Output should obviously be 3;
auto result = find_if(myVector.begin(), myVector.end(),
[](const auto& x){ return x->endpoint == 9; });
if (result != myVector.end())
{
std::cout << "Found: " << (*result)->endpoint
<< " @ index " << (result - myVector.begin()) << std::endl;
}
else
{
std::cout << "Not Found" << std::endl;
}
return 0;
}
Re: Using Lambdas to search a std::vector for an object ... (Help)
Hey Laserlight.... I sincerely appreciate your kind response. I learn by example and that one is one of the best. I always like to repay the kindness of others when it comes to things like this. If you have a PayPal account I'd like to send you $20 USD for your trouble.