【问题标题】:Passing a member function with two parameters to C++ STL algorithm stable_partition将带有两个参数的成员函数传递给 C++ STL 算法 stable_partition
【发布时间】:2015-10-27 17:43:25
【问题描述】:

我的成员函数如下

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;
}

使用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。任何指针?

【问题讨论】:

  • 另一个问题:为什么要在这一行中写类名 std::vector foo::extractAgents(int id);
  • bool foo::isNotEqualId(const Agent&amp;, const int id) 缺少标识符,可能是代理。是错字吗?你得到什么错误?
  • 是的,打错了,刚刚更新

标签: c++ stl stl-algorithm


【解决方案1】:

由于您使用的是 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,非常感谢,它成功了!
【解决方案2】:

你可以使用lambda:

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

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

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多