Sign in to follow this  
Xmon

std::find and struct

Recommended Posts

This is not a big thing, but I allways like to know:) I got a std::vector with struct's. Can I use std::find or any other built in algorithm to find an element whit a specific value? For example:
struct T
{
 int i;
 float f;
};
std::vector<T> test;
// How do I find the first element with i==3?


Share this post


Link to post
Share on other sites
Couple ways to do it. The stupid way--defining an operator== which tests only that element--works, but it's ugly and doesn't allow you to search by more than one field. The better way is to define a functor and use find_if. Behold!

struct Foo
{
int a, b;
};

class AEquality
{
public:
AEquality(int a) : m_a(a) { }

bool operator() (const Foo &elem) { return elem.a == m_a; }

private:
int m_a;
};

std::vector<Foo> foos;

...

std::find_if(foos.begin(), foos.end(), AEquality(3))



For more on what's going on here, read up on find_if and also read up on functors.

Share this post


Link to post
Share on other sites
If you are willing to use an extension library, you can do:

#include <boost/bind.hpp>
using namespace boost;
...

std::find_if(test.begin(), test.end(), bind(&Foo::i, _1) == 3 )



bind is a function that creates functors.

&Foo::i is a member variable pointer.
_1 is a placeholder for the first parameter of the functor being created.

Together, bind(&Foo::i, _1) creates a functor that returns the i member of the Foo (or Foo*) parameter being passed.

An overload is conveniently provided to turn it into a comparison predicate, so that bind(&Foo::i, _1) == 3 is a function object that compares i with 3.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this