std::find and struct

Started by
2 comments, last by Fruny 17 years, 7 months ago
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?


Advertisement
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.
Thanks, I'll try that
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement