2013-05-02 73 views
-1

我的问题在很多方面类似于这个:Pass a custom comparator through a function,但我尝试了在那里提出的解决方案,并且无法使其工作。自定义比较(订购)作为(多)地图订购参数?

概括地说,我有保持几个排序的结构和执行若干比较,始终使用相同的排序int类型,所有的元件的方法。当该方法被称为时确定的排序是

打算调用看起来是这样的:myFunction(std::greater<int>());

首先,我想声明的功能:void myFunction(binary_operator<int, int, bool> order);但是,按照this explanationbinary_function不适合充当函数调用基类。

最后,我试图从this answer(和许多其他网站)的建议,使用模板这表明。但是,我仍然无法让我的代码编译。

最小非工作例如:

template <typename Comparator> 
void myFunction(Comparator order){ 

    if (order(1,2)){ 
     // some stuff 
     // COMPILES OK 
    } 

    std::vector <int> vecToSort; 
    // ... initialize 
    std::sort(vecToSort.begin(), vecToSort.end(), order); // works 
    // COMPILES OK 

    std::multimap <int, int, order > boundary; 
    // STARTS KICKING, SCREAMING AND SHOUTHING 
} 

和编译错误,我得到:

error: type/value mismatch at argument 3 in template parameter list for ‘template class std::multimap’ error: expected a type, got ‘order’

我想通了同样的伎俩应该都正常工作。它不是。 (编辑:我可以看到现在type/object问题)

有人可以请解释这里发生了什么,并如何获得multimap使用作为函数参数传递的顺序?

PS:我没有使用这个项目的助推器。

std::multimap <int, int, Comparator> boundary(order); 
         ^^^^^^^^^^ 

正如评论说,你需要提供一个type不是object

+0

错误很明显,顺序是一个对象不是一个类型,因此不能被传入模板参数。 – yngccc 2013-05-02 16:17:45

+0

'std :: multimap'需要一个**类型**作为模板参数,并且您正在使用一个对象。 – juanchopanza 2013-05-02 16:18:47

+0

好的,我看到类型/对象问题。但是,这只是回答*为什么*我得到的错误,而不是如何使用我想要的顺序(作为函数参数传递)来订购我的结构,包括'multimap'。 – penelope 2013-05-02 16:24:15

回答

2

如下应当申报。这些文档为Construct multimap提供了一些示例。

+0

好吧,我看到类型/对象的问题。但是,像这样,'multimap'中的元素具有哪种精确排序?如何实现它们在函数调用中作为函数参数传递的顺序? – penelope 2013-05-02 16:21:56

+0

@penelope错字的道歉,我只是修复它。 – 2013-05-02 16:23:28

+1

@penelope只需通过如上所示的实例化,传递'order'作为构造函数参数。见[这里](http://en.cppreference.com/w/cpp/container/map/map)。 – juanchopanza 2013-05-02 16:26:18

2

使用Comparatororder以这种形式:

std::multimap <int, int, Comparator> boundary (order); 

首先通过比较类型里面<>,然后通过比较对象的构造函数。