struct T
{
int i;
float f;
};
std::vector<T> test;
// How do I find the first element with i==3?
std::find and struct
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:
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!
For more on what's going on here, read up on find_if and also read up on functors.
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.
If you are willing to use an extension library, you can do:
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.
#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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement