c++ - 如何将 sort() 的比较参数与模板和自定义数据结构一起使用

标签 c++ templates sorting stl

我想创建一个比较函数对象来帮助我对自定义数据结构的 vector 进行排序。由于我同时使用模板,因此我正在努力弄清楚应该在哪里实现它以及需要任何其他代码。下面的大部分代码都可以忽略。包含它是为了完整性,但在 printSummary() 的最后使用了比较函数对象。简而言之,如何实现比较函数对象?

#include<map>
#include<vector>
//#include<iostream>
#include<algorithm>
using namespace std;

template <class T>
class Record{
   public:
   T item;
   int total;
};

   template<class T>
   bool compare(const Record<T> & a, const Record<T> & b){ //should a come before b?
      if(a.total > b.total)
         return true;
      if(a.total < b.total)
         return false;
      if(a.total == b.total){
         if(a.item < b.item)
            return true; 
         else
            return false;
      }
   }

template <class T>
class Counter{
   public:
      map<T, int> m;

   void printSummary(){

      typename map<T, int>::const_iterator itr; 
      vector< Record<T> > printlist;
      Record<T> temp;
      int i = 0;

      for( itr = m.begin(); itr != m.end(); ++itr ){
         temp.item = (*itr).first;
         temp.total = (*itr).second;
         printlist.push_back(temp);
         i++;
      }

      sort(printlist.begin(), printlist.end(), compare);

      //output sorted printlist contents
   }

};

最佳答案

在您调用 sort() 时,您正在指定一个函数的名称​​模板 而不实例化它:

sort(printlist.begin(), printlist.end(), compare);
//                                       ^^^^^^^

函数模板的裸名代表编译器的整个重载集(其中该集包括该模板的所有可能特化)。

要消除歧义,需要实例化compare<>()为了提供一个函数的地址:

sort(printlist.begin(), printlist.end(), compare<T>);
//                                              ^^^

或者,您可以制作compare一个仿函数:

struct compare
{
   template<class T>
   bool operator () (const Record<T> & a, const Record<T> & b)
   {
      // should a come before b?
      if(a.total > b.total)
         return true;
      if(a.total < b.total)
         return false;
      if(a.total == b.total){
         if(a.item < b.item)
            return true; 
         else
            return false;
      }
   }
};

然后,您可以将其传递给 sort()这样,无需模板实例化(但您需要创建仿函数的实例,尽管临时的很好,如下所示):

sort(printlist.begin(), printlist.end(), compare());
//                                       ^^^^^^^^^

关于c++ - 如何将 sort() 的比较参数与模板和自定义数据结构一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15988345/

相关文章:

java - 二分查找CompareTo Java

c# - .NET 访问 802.15.4 无线收发器

c++ - C++ 中的虚函数和模板——它们可以被其他(C++ 中存在的)操作替换吗?

c++ - 创建一个真正的 headless QApplication 实例

c++ - 根据模板变量类型执行不同的方法

c++ - 具有不同参数列表的模板对象的模板静态映射

mongodb - 按与 MongoDB 的相关性排序

r - 如何有效地排序R中字符串中的字符?

c++ - 使用 VSC++ 代码在 Pocket PC 上播放 mp3

c# - 想在 asp.net 中使用 c++ 库和 dll