我與鄰接表工作並用下面的類型定義定義的地圖排序: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