在vector上查找并比较成员变量

find_if on vector and compare member variables

本文关键字:比较 成员 变量 查找 vector      更新时间:2023-10-16

我有一个这样的课堂场景:

class Renderer;
class Scene
{
public:
    Scene(const std::string& sceneName);
    ~Scene();
    void Render(Renderer& renderer);
    Camera& GetSceneCamera() const;
    SceneNode& GetRootNode() const;
    const std::string& GetSceneName() const;

private:
    const std::string mName;
    Camera mSceneCamera;
    SceneNode mRootNode;
};

然后我有一个场景向量(vector<Scene>)。

现在给定一个字符串,我想遍历这个场景向量,如果在场景中找到名称,返回一个指向它的指针。这是一个幼稚的尝试,但我得到编译错误:

Scene* SceneManager::FindScene(const std::string& sceneName)
{
    return std::find_if(mScenes.begin(), mScenes.end(), boost::bind(&std::string::compare, &sceneName, _1));
}

Boost正在抱怨参数的数量,所以我一定是语法错误。正确的做法是什么?

编辑:No instance of overloaded boost::bind matches the argument list

EDIT2: Not c++ 11

谢谢

让我们一步一步来。

find_if将对vector中的每个元素调用比较函数,当比较函数返回true时停止。该函数需要通过const Scene &参数来调用。

我们可以这样写(所有这些代码都是未经测试的):

struct SceneComparatorName {
    SceneComparatorName ( std::string &nameToFind ) : s_ ( nameToFind ) {}
    ~SceneComparatorName () {}
    bool operator () ( const Scene &theScene ) const {
        return theScene.GetSceneName () == s_;
        }
    std::string &s_;
    };

现在-你怎么写内联?您对boost::bind的尝试失败了,因为您错过了对GetSceneName的调用,并且您无法将Scene &std::string进行比较

c++ 11

很容易编写一个lambda来完成上面的结构体的功能。

[&sceneName] (const Scene &theScene ) { return theScene.GetSceneName () == sceneName; }

但是你不想要c++11,所以你必须这样写:

boost::bind ( std::string::operator ==, sceneName, _1.GetSceneName ());

,但这不起作用,因为它将在bind调用中调用GetSceneName,而不是在调用bind创建的函函数时调用。

然而,

增加。Bind支持重载操作符,所以你可以这样写:

    boost::bind ( &Scene::GetSceneName, _1 ) == sceneName

和完成。

最短的方法可能是手动循环:

BOOST_FOREACH(Scene& scene, mScenes) {
    if (scene.GetSceneName() == sceneName) return &scene;
}
return 0;