我有以下資料結構(第一個字串作為學校的“主題”)
map<string, vector<School>> information;
學校是:
struct School {
string name;
string location;
}
我無法按字母順序列印整個資料結構(首先是主題,然后是位置,然后是名稱)。舉個例子。
"map key string : struct location : struct name"
"technology : berlin : university_of_berlin"
到目前為止,我設法通過初始地圖回圈
for (auto const key:information) {
//access to struct
vector<School> v = key.second;
//sorting by location name
//comparasion done by seperate function that returns school.location1 < school.location2
sort(v.begin(), v.end(), compare);
如果我列印出主題 (key.first) 和 v.location,就差不多完成了。默認情況下對地圖進行排序,并且位置比較有效。但我不知道如何按名稱添加第二個比較。如果我再進行一次排序,這次是按名稱排序,那么我會丟失按位置的原始順序。是否有可能在一個標準更重要的情況下“雙重排序”,然后是另一個?
uj5u.com熱心網友回復:
對此有一個簡單的答案,我假設您想在"location"then 之前先訂購"name"。
簡單的方法是在struct School結構中實作一個less運算子。
示例代碼:
//in School.hpp
struct School {
string name;
string location;
bool operator<(const School& rhs) const;
}
//in School.cpp
bool School::operator<(const School& rhs) const {
if(this->location < rhs.location)
return true;
if(rhs.location < this->location)
return false;
if(this->name < rhs.name)
return true;
if(rhs.name < this->name)
return false;
return false;
}
但是還有其他方法,您現在可以像這樣呼叫 sort 。
sort(v.begin(), v.end());
uj5u.com熱心網友回復:
可以,你只需要添加一些條件 compare
bool compare(School const& lhs, School const& rhs)
{
if(lhs.location != rhs.location)
return lhs.location < rhs.location)
return lhs.name < rhs.name
}
或者你可以<像@ceorron 那樣多載運算子
uj5u.com熱心網友回復:
我添加這個答案只是為了迂腐。請參閱JustANewbie 的回應,了解對這種特殊情況的正確做法(我會在大多數正常情況下說)。
執行多遍排序是完全可能的。訣竅是對每個額外的傳遞使用穩定的排序方法。(穩定的排序保留等效元素的相對順序。)
默認std::sort演算法是 Introsort——它不是一種穩定的排序(它使用快速排序 插入排序,但如果快速排序需要更長的時間,則會切換到堆排序)。
方便的是,標準庫為我們提供std::stable_sort了何時需要穩定排序的演算法。
穩定排序通常比非穩定排序慢,這就是為什么我們傾向于盡可能選擇非穩定排序。第一遍您可以使用非穩定排序,但您必須對所有其他遍使用穩定排序。
std::sort ( xs.begin(), xs.end(), compare_names ); // 1st pass: secondary criterion
std::stable_sort( xs.begin(), xs.end(), compare_locations ); // 2nd pass: primary criterion
最終訂單將主要按位置排序,其次按名稱排序。
您可以根據需要添加任意數量的排序程序。請記住,您以與它們的重要性相反的順序應用通行證。例如,如果要按(姓氏、名字、年齡)對人員進行排序,則必須按相反的順序應用排序:年齡、名字、姓氏。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339868.html
上一篇:根據用戶輸入創建元素的子串列
