将带有两个参数的成员函数传递给 C++ STL 算法 stable_partition

Passing a member function with two parameters to C++ STL algorithm stable_partition

我有成员函数如下

class foo 
{
    public:
        ...
        bool isNotEqualId(const Agent&, const int);
        std::vector<Agent> foo::extractAgents(int id);
    private:
        std::vector<Agent> agents;
}

函数定义如下:

bool foo::isNotEqualId(const Agent& agent, const int id)
{
    return (agent.groupId != id);
} 

现在,在 foo 中,我根据代理 ID 对代理进行分区,以便稍后在给定另一个参数的情况下提取它们。

std::vector<Agent>& foo::extractAgents(int id)
{
    std::vector<Agent>::iterator iter = std::stable_partition(agents.begin(), agents.end(), &foo::isNotEqualId(id));

    // Partition to find agents that need to be removed
    std::vector<Agent>::iterator extractedGroupiter = std::stable_partition(iter, agents.end(), keepAgent);
    // Create a vector with the agents that need to be removed
    std::vector<Agent> extractedGroup(extractedGroupiter, agents.end());
    // Erase them from the agents vector
        agents.erase(extractedGroupiter, agents.end());
        return extractedGroup;
}

using std::stable_partition 用于具有固定组值的函数,例如

bool isNotGroup0(const Agent& a)
{
    return a.groupId != 0;
}

但是,现在我想使用一个有两个参数的成员函数,所以组ID可以作为一个参数。 stable_partition 采用一元谓词,这导致了我的问题。我尝试将 std::bind2ndstd::mem_fun 一起使用,以便在将第二个参数传递给 stable_partition 时绑定第二个参数,但它会导致 mem_fun 没有重载实例的错误功能。

我也尝试过仿函数解决方案,例如 here,它建议使用 std::binary_function,但它会导致错误 term does not evaluate to a function taking 1 arguments,这是可以理解的。我正在使用 VS2010。任何指针?

由于您使用的是 Visual Studio 2010,我不知道该版本是否提供 lambda,因此请使用函数对象:

struct AgentFunctor
{
   int id_;
   AgentFunctor(int id) : id_(id) {}
   bool operator()(const Agent& agent) const
   { return agent.groupId != id_; }
};
//...
AgentFunctor af(id);
std::vector<Agent>::iterator iter = std::stable_partition(agents.begin(), agents.end(), af);

您可以只使用 lambda:

std::stable_partition(agents.begin(), agents.end(),
                      [nGroupID, foo](x){
                        return foo.isNotEqualID(x, nGroupID);});

刚刚注意到 VS2010 评论,我很确定它没有 lambda,在这种情况下,您必须更加手动地创建函数对象,例如 PaulMcKenzie 的回答。