简体   繁体   English

使用匹配的字符串搜索结构的c ++ std向量

[英]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: 我正在尝试使用“std :: find”搜索mJointsVector以通过其字符串名称找到一个单独的关节 - 到目前为止没有运气,但以下示例有助于,至少在概念上:

Vectors, structs and std::find 向量,结构和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. 或者,您可能希望查看类似Boost.Bind的内容以减少代码量。

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. 然后你可以使用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")) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM