2014-02-21 43 views
0

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

所以我想使用與鄰接列表索引相關的名稱對鄰接列表進行排序。我已經拿出了下面的代碼。由於我的比較功能需要地圖,我不能只是創建一個正常的功能。所以我用了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)); 

    ... 
    } 
+0

返回的值,但原來是從來沒有被覆蓋。你通過引用傳遞,但不作任何分配。 – OJFord

+0

@OllieFord,我認爲比較函數只是簡單地返回兩個對象的真/假,算法'sort'將使用該返回值進行排序。我的函數是否需要修改傳遞的對象? –

+0

對不起,你說得很對,我誤解了。實際的問題是'Local(page_ofID)== True',換句話說'sort()'的第一個參數總是被認爲小於第二個。因此,當它完成「排序」時,就完成了將它們按照它們已經處於相同的順序完成的步驟。編寫一個執行比較的函數可能會更好,但可以從「printOrganised」和「sortCities」中調用它們。 (或任何名字)的功能。 – OJFord

回答

1

在修復編譯錯誤後,我的代碼對我很好用。也許你的編譯器不報告這個錯誤,但它導致你的代碼不工作?

不管怎樣,錯誤是比較功能 - 你應該得到這兩個參數爲const引用,即

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

此外,我不得不搬到Local在全球範圍內,因爲它不是爲工作只要它是在函數內部定義的。你可以看到這裏的工作結果:http://ideone.com/e.js/UPMeFm

+0

感謝您測試代碼PaF!我看了一下'Local'的包裝器,顯然問題來自於我從'page_ofID'獲取頁面的方式。我使用'page_ofID.at(iter-lst.begin())'而不是'page_ofID.at(iter-> front()。origin);'。 –