簡體   English   中英

如何通過將第一個插入保留在其 position 中來對插入列表中的元素的 rest 進行排序?

[英]How do I sort rest of the elements that I insert in a list by keeping the first insertion remain in its position?

假設我正在嘗試使用包含列表在 CPP 中的列表中插入隨機內容,

list <string> newList;
list<string>::iterator z = newList.begin();
//James(Remains static, rest sorted)  -> Abraham-> Brian-> Chuck-> David-> Rick-> Morty
newList.insert(z,James);
newList.insert(z,David);
newList.insert(z, Rick);
newList.insert(z, Abraham);
newList.insert(z, Brian);
newList.insert(z, Morty);
newList.insert(z, Chuck);

如何以及在哪里調用 newList.sort() 以使除第一個插入(即詹姆斯)之外的所有這些都排序?

這是一個潛在的解決方案,首先刪除第一個條目,然后進行排序。

auto front = newList.front();
newList.pop_front();
newList.sort();
newList.push_front(front);

這將使整個列表排序,但開頭的任何內容(在您的示例中為James )都將重新添加到列表的前面。

保留第一個元素的 position 的簡單解決方案:

  • 將迭代器存儲到第一個元素
  • 對列表進行排序
  • 將存儲的迭代器中的元素拼接回開頭

如果“第一個插入”不是第一個元素 - 畢竟元素可以插入到任意位置 - 那么需要更復雜的邏輯。

不幸的是,標准庫中似乎不存在用於子列表的通用排序算法。

使用自定義比較器,將James置於所有其他人之前:

bool compare(const std::string& a, const std::string& b) {
    if (a == b) return false;
    else if (a == James) return true;
    else if (b == James) return false;
    else return a < b;
}

您需要注意a==b的情況以進行嚴格的弱排序( James < James必須返回false )。 然后James在所有其他人之前,所有其他人都在James之后,否則您只需比較這兩個元素。

請注意,如果列表中有多個James ,則通過此比較,它們都將排在前面,因此它並沒有完全按照您的要求進行。

 auto first = newList.front();
 newList.sort();
 cout<<first<<" ";
 for(auto it :newList)
    cout<<it<<" ";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM