2016-12-15 17 views
0

不可用的元素我試圖從我的無序映射中包含映射到包含類T,int和sortBy作爲比較類的映射的映射。從無序地圖創建具有自定義類作爲關鍵字的地圖。然而由於const

但是我不能對地圖中的任何元素執行任何函數,因爲它們都是const。我不知道如何讓它們不是常量,或者爲什麼它們是常量。

unordered_map < int,LibrarySong> Library; 
map < LibrarySong,int, LibrarySong:: sortbyPlay> sortedLibrary; 

for(unordered_map<int,LibrarySong>:: iterator it = Library.begin(); it != Library.end(); ++it){ 
    sortedLibrary.insert(pair <LibrarySong,int> (it->second, it->first)); 
} 
for(map < LibrarySong,int>::iterator it=sortedLibrary.begin(); it != sortedLibrary.end(); ++it){ 
    cout << it->first.print() << endl; //Cant do anything because it is const 
}; 

的LibrarySongs頭具有結構

struct sortbyPlay { 
    bool operator() (const LibrarySong &lhs ,const LibrarySong &rhs) const{ 
     return lhs.numPlay < rhs.numPlay; 
    } 
}; 

我試圖消除在函數中常量但也不起作用?

也許有更好的方法來做到這一點,我不確定。我正在考慮矢量,然後使用sort(),但我需要兩個值(可能可以使用一對?),但我不確定const問題是否仍然存在。

+0

在我看來,你讓事情變得不必要的複雜。您的unordered_map使用int作爲鍵,並使用Librarysong實例作爲值。你的地圖切換,然後使用一個特殊的比較器。 numPlay是int嗎?如果是這樣,爲什麼不把它作爲關鍵,並得到你想要的排序,LibrarySong不再是常量。 – tinstaafl

回答

0

const-map的比較器的性質完全不相關。

cout << it->first.print() << endl; //Cant do anything because it is const 

地圖的按鍵,first值,總是const。因此,該類中的print()方法必須是const方法。雖然您的問題完全無法提供minimal, complete, and verifiable example,但顯然您的print()方法必須是const方法,而不是。

類方法,如print(),不需要修改其對象。至少不是一個理智的班級設計。因此,您不應該有任何問題將print()方法聲明爲const類方法。