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