开发者

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 st开发者_如何学编程ring 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?


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.


how about:

std::string name = "xxx";

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


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.


#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);


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

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


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")) ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜