7

我敢肯定,我让这件事变得比需要的更难。

我有一个矢量...

vector<Joints> mJointsVector;

...由以下模式的结构组成:

struct Joints
{
    string name;

    float origUpperLimit;
    float origLowerLimit;   
};

我正在尝试使用“std::find”搜索 mJointsVector 以通过其字符串名称定位单个关节 - 到目前为止还没有运气,但以下示例至少在概念上有所帮助:

向量、结构和 std::find

谁能进一步指出我正确的方向?

4

6 回答 6

16

直截了当的方法:

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()) {
    // ...
}

或者,您可能想研究Boost.Bind之类的东西来减少代码量。

于 2010-01-08T06:46:10.363 回答
5

怎么样:

std::string name = "xxx";

std::find_if(mJointsVector.begin(), 
             mJointsVector.end(), 
             [&s = name](const Joints& j) -> bool { return s == j.name; }); 
于 2010-01-08T07:02:43.820 回答
1

您应该能够添加一个等于运算符来执行您的结构

struct Joints
{
    std::string name;

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

然后您可以使用 find 进行搜索。

于 2010-01-08T06:59:02.537 回答
1
#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);
于 2010-01-08T19:29:10.100 回答
0
bool
operator == (const Joints& joints, const std::string& name) {
    return joints.name == name;
}

std::find(mJointsVector.begin(), mJointsVector.end(), std::string("foo"));
于 2010-01-08T06:50:44.970 回答
0
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")) ;
于 2010-01-08T07:33:48.193 回答