Jump to content
  • Advertisement
Sign in to follow this  
Xmon

std::find and struct

This topic is 4482 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!