在vector上查找并比较成员变量
find_if on vector and compare member variables
我有一个这样的课堂场景:
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
进行比较
很容易编写一个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;
相关文章:
- 三向比较运算符成员与非成员实现
- 用于基于成员字段或函数创建比较器的快捷方式
- 如何通过比较彼此的成员从QStringList中删除元素
- 在单元测试中,如何在不使用 operator== 的情况下比较两个对象,这可能会错过新成员?
- 重载对象成员的比较运算符
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 将比较器传递给Priority_queue,称为班级成员
- 具有多个空成员的 std::元组上的比较无法在 GCC 上编译
- 标准::元组成员逐个成员比较失败
- 通过构造函数与直接初始化进行成员初始化的比较
- 为什么比较和交换操作同时存在免费函数和成员函数?
- 没有成员作为唯一标识符的两个类实例的比较
- 将对象成员数组与字符串进行比较
- 比较存储在向量中的类对象的私有成员变量 - C++
- 将非静态数据成员与常量成员进行比较
- 比较成员函数的 std::函数
- c++ std::sort():仅使用一个比较函数的任何可比较成员的对象向量
- 如何比较成员指针函数与Microsoft Visual C中涉及的dll是否相等
- 为什么比较成员函数指针为NULL会产生警告?
- 在vector上查找并比较成员变量