Monte Hurd
Monte Hurd

Reputation: 4437

Searching c++ std vector of structs for struct with matching string

I'm sure I'm making this harder than it needs to be.

I have a vector...

vector<Joints> mJointsVector;

...comprised of structs patterned after the following:

struct Joints
{
    string name;

    float origUpperLimit;
    float origLowerLimit;   
};

I'm trying to search mJointsVector with "std::find" to locate an individual joint by its string name - no luck so far, but the examples from the following have helped, at least conceptually:

Vectors, structs and std::find

Can anyone point me further in the right direction?

Upvotes: 7

Views: 9097

Answers (6)

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

A straight-forward-approach:

struct FindByName {
    const std::string name;
    FindByName(const std::string& name) : name(name) {}
    bool operator()(const Joints& j) const { 
        return j.name == name; 
    }
};

std::vector<Joints>::iterator it = std::find_if(m_jointsVector.begin(),
                                                m_jointsVector.end(),
                                                FindByName("foo"));

if(it != m_jointsVector.end()) {
    // ...
}

Alternatively you might want to look into something like Boost.Bind to reduce the amount of code.

Upvotes: 16

mukeshkumar
mukeshkumar

Reputation: 2778

struct Compare: public unary_function <const string&>
{
     public:
            Compare(string _findString):mfindString(_findString){}
            bool operator () (string _currString)
            {
                return _currString == mfindString ;
            }
     private:
            string mfindString ;
}

std::find_if(mJointsVector.begin(), mJointsVector.end(), Compare("urstring")) ;

Upvotes: 0

Matthieu N.
Matthieu N.

Reputation:

how about:

std::string name = "xxx";

std::find_if(mJointsVector.begin(), 
             mJointsVector.end(), 
             [&s = name](const Joints& j) -> bool { return s == j.name; }); 

Upvotes: 5

Fred
Fred

Reputation: 1448

#include <boost/bind.hpp>

std::vector<Joints>::iterator it;

it = std::find_if(mJointsVector.begin(),
                  mJointsVector.end(),
                  boost::bind(&Joints::name, _1) == name_to_find);

Upvotes: 1

Jason T.
Jason T.

Reputation: 382

You should be able to add a equals operator do your struct

struct Joints
{
    std::string name;

    bool operator==(const std::string & str) { return name == str; }
};

Then you can search using find.

Upvotes: 1

Andreas Brinck
Andreas Brinck

Reputation: 52519

bool
operator == (const Joints& joints, const std::string& name) {
    return joints.name == name;
}

std::find(mJointsVector.begin(), mJointsVector.end(), std::string("foo"));

Upvotes: 0

Related Questions