gpt4 book ai didi

c++ - 在 C++ 类中使用谓词函数指针

转载 作者:行者123 更新时间:2023-11-28 03:35:48 26 4
gpt4 key购买 nike

我正在尝试使用 this 中提供的解决方案类里面的问题。我在类中使用了带有谓词函数的“remove_if”。

    void classname::function1()
{
vector<NeighborPoint> neighbors;
....
neighbors.erase(std::remove_if(neighbors.begin(),neighbors.end(),&classname::cannotMoveIn), neighbors.end());
...
}

bool classname::cannotMoveIn(NeighborPoint mp)
{
return !mp.inGridNotOccupied;
}

如果该代码不在类中并且谓词不是成员函数,则该代码将起作用。但是,现在我收到很长的错误消息,我猜这是指 remove_if 模板与谓词参数不兼容(一个错误包括:error C2064:term does not evaluate to a function taking 1 arguments)。

注意:代码旨在移除代理无法进入的相邻网格单元(8 个可能的单元格中)。

有没有人知道哪里出了问题?

最佳答案

That code would work if it was not in a class and the predicate was not a member function.

当然。实例方法不像全局函数;它为 this(它被调用的对象)带了一个额外的隐藏参数。但似乎你根本不需要在你的函数中使用当前对象。为什么首先将其设为实例方法?

如果您不需要使用this,那么您可以做的一件事就是使它成为一个静态方法(这就像一个常规函数,除了作用域)。然后你可以像以前一样像普通函数一样传递它。比谓词函数更好的是使用函数对象(你必须定义一个仿函数类,如果你不想将它移出类,它甚至可以是一个嵌套类)或一个 lambda(如果你有 C++11),这将允许谓词内联到删除算法中,因此比每次都必须调用函数指针更快。

关于c++ - 在 C++ 类中使用谓词函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10924927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com