【问题标题】:C++ STL Comparison class: how to parameterize comp-class behaviour?C ++ STL比较类:如何参数化comp类行为?
【发布时间】:2011-03-28 02:01:01
【问题描述】:

我想使用具有自定义数据类型和几个比较标准的 std::priority_queue 容器(我为它们中的每一个定义了一个仿函数;它们中的每一个都在处理相同的类型)。 使用的比较标准本身应该可以通过函数参数进行配置(避免队列的 if_then_ 初始化)。

基于this post,据我所知,使用比较函子,它本身是用指向已定义比较函数之一的函数指针初始化的,我尝试使用可配置的比较函子,它用另一个比较函子初始化(然后存储在本地并在调用时使用)。我还没有让它工作。

我什至不知道是否可以做我想做的事情。我不知道我是否在类型方面做错了(我使用了 typedef boost::function xxx)或需要额外的 C++0x 功能(“闭包”有帮助吗?)。

所以基本上我希望有类似以下的工作(这不会编译一个非长但丑陋的错误;GCC 4.5):

#include <iostream>
#include <queue>
#include <boost/tuple/tuple.hpp>
#include <boost/function.hpp>

typedef boost::tuple<double, int> custom_type;  // example only!
typedef boost::function<bool (const custom_type & l, const custom_type & r)> comp_type; // comparison functor

struct fifo_comp
{
    bool operator() (const custom_type & l, const custom_type & r) const
    {
        // compare only id
        return l.get<1>() > r.get<1>();
    }
};

struct lifo_comp
{
    bool operator() (const custom_type & l, const custom_type & r)
    {
        // compare only id
        return l.get<1>() < r.get<1>();
    }
};

class Compare
{
    public:
        explicit Compare(const comp_type & comp);

        bool operator() (const custom_type & l, const custom_type & r)
        {
            return comp(l, r);
        }

    private:
        const comp_type & comp;
};

class Some_Class_Using_Queue
{
public:
    Some_Class_Using_Queue(comp_type & comp) : pqueue(Compare(comp)) {}

    void test()
    {
        pqueue.push(custom_type(1.0, 1));
    }

private:
    std::priority_queue<custom_type, std::vector<custom_type>, Compare> pqueue;
};

int main()
{
    comp_type f = fifo_comp();
    Some_Class_Using_Queue temp((f));    // critical
    temp.test();
    return 1;
}
  • 任何帮助让它为我工作(鼓励使用 STL/Boost)?
  • 有更好的想法(完全不同)吗?
  • 这里有什么很酷的 C++0x 功能可以提供帮助(可能是闭包)?

谢谢。

PS/Edit:我知道,使类模板化并使用适当的 comp-class 作为模板参数调用类是可能的并且非常容易。但我不知道这是否是更好的方法(关于设计)。使用这种方法,我必须在调用之前切换/if-else,因为模板参数需要在编译时可用。

PS:我设置了“priority_queue”标签,即使问题可能完全独立于这个适配器类。如果有人想删除它,那就去做吧。

【问题讨论】:

    标签: c++ boost stl c++11 priority-queue


    【解决方案1】:

    你缺少Compare的构造函数的定义:

    explicit Compare(const comp_type & comp) : comp(comp) { }
    

    除此之外,它为我构建和运行。

    另外,Compare 似乎是多余的。它只是用相同的接口包装了 comp_type。在删除 Compare 类并将其替换为 comp_type 之后,代码仍然可以构建和运行。

    【讨论】:

    • 好的,这很简单。现在正在编译。感谢您的快速回答。
    • explicit 关键字仅表示在需要转换时不能隐式调用它。您仍然需要提供定义。您现有的代码是有效的,但它仅声明构造函数;它没有定义它。因此,我看到的错误是链接阶段缺少符号(构造函数),而不是编译器错误。
    • 是的,我误读了你的答案,编辑我的评论太晚了。但再次感谢您的澄清。现在一切正常。
    • 再次感谢您提供的额外“冗余”提示。我想我在某种程度上受到了我发布的链接的影响,并想将它 1:1 翻译成函子。
    猜你喜欢
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2016-03-10
    相关资源
    最近更新 更多