C++ - 使用额外参数进行排序

C++ - Sorting with an extra parameter

本文关键字:参数 排序 C++      更新时间:2023-10-16

我正在使用邻接列表和使用以下类型定义定义的映射:

typedef vector<list<Edge> > adjacencyList;
typedef map<int,WikiPage> idToWikiMap;

我想按名称对邻接列表(adjacencyList)进行排序。adjacencyList的索引映射到我的地图中的一对。例如

adjacencyList lst;
lst[0] = NULL
lst[1] = list of edges related to City1
lst[2] = list of edges related to City2
idToWikiMap mymap;
mymap[1] -> Name of City1
mymap[2] -> Name of City2

因此,我想使用与邻接列表索引相关的地图中的名称对邻接列表进行排序。我想出了以下代码。由于我的比较函数需要映射,所以我不能只创建一个普通函数。所以我用了structLocal.

比较有效。我可以cout当前正在比较的列表的名称和返回值。例如,我得到

Comparing Chicago and  New York
Smaller: 0
Comparing Montreal and  Chicago
Smaller: 1
Comparing Montreal and  New York
Smaller: 0
Comparing Toronto and  Chicago
Smaller: 1
Comparing Toronto and  Montreal
Smaller: 1
Comparing Toronto and  New York
Smaller: 1
Comparing Miami and  Chicago
Smaller: 1
Comparing Miami and  Montreal
Smaller: 0

但是,原始版本不会被修改...我做错了什么吗?

  void printOrganized(adjacencyList& lst, idToWikiMap page_ofID) {
  // Define compare functions that accepts idToWikiMap parameter
  struct Local {
    Local(idToWikiMap mymap) { this->mymap = mymap; }
    bool operator() (const list<Edge>& l1, list<Edge>&l2)
    { return mymap.at(l1.front().origin).title < mymap.at(l2.front().origin).title; }
    idToWikiMap mymap;
  };
  /* Sort adjacenyList lst */
  sort (lst.begin()+1, lst.end(), Local(page_ofID));
  ...
  }

在我修复编译错误后,您的代码对我来说效果很好。也许您的编译器没有报告此错误,但它导致您的代码无法正常工作?

无论如何,错误出在比较函数中 - 您应该将两个参数都作为 const 引用,即

bool operator() (const list<Edge>& l1, const list<Edge>& l2)

此外,我不得不Local移动到全局范围,因为只要它在函数中定义,它就对我不起作用。您可以在此处查看工作结果:http://ideone.com/e.js/UPMeFm