我与邻接表工作并用下面的类型定义定义的地图排序:C++ - 有一个额外的参数
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
所以我想使用与邻接列表索引相关的名称对邻接列表进行排序。我已经拿出了下面的代码。由于我的比较功能需要地图,我不能只是创建一个正常的功能。所以我用了struct
和Local
。
的比较的作品。我可以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));
...
}
返回的值,但原来是从来没有被覆盖。你通过引用传递,但不作任何分配。 – OJFord
@OllieFord,我认为比较函数只是简单地返回两个对象的真/假,算法'sort'将使用该返回值进行排序。我的函数是否需要修改传递的对象? –
对不起,你说得很对,我误解了。实际的问题是'Local(page_ofID)== True',换句话说'sort()'的第一个参数总是被认为小于第二个。因此,当它完成“排序”时,就完成了将它们按照它们已经处于相同的顺序完成的步骤。编写一个执行比较的函数可能会更好,但可以从“printOrganised”和“sortCities”中调用它们。 (或任何名字)的功能。 – OJFord