Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Monte Hurd Avatar asked Jan 08 '10 06:01

Monte Hurd


1 Answers

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.

like image 151
Georg Fritzsche Avatar answered Sep 19 '22 14:09

Georg Fritzsche