[英]How do I sort rest of the elements that I insert in a list by keeping the first insertion remain in its position?
Suppose I'm trying to insert random stuff on a list in CPP using include list,假设我正在尝试使用包含列表在 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);
how, and where do I call the newList.sort() to make all of them sorted except the first insertion, ie James?如何以及在哪里调用 newList.sort() 以使除第一个插入(即詹姆斯)之外的所有这些都排序?
Here's a potential solution, by first removing the first entry, then sorting.这是一个潜在的解决方案,首先删除第一个条目,然后进行排序。
auto front = newList.front();
newList.pop_front();
newList.sort();
newList.push_front(front);
This will make the entire list sorted, but whatever was at the beginning ( James
in your example) will be re-added to the front of the list.这将使整个列表排序,但开头的任何内容(在您的示例中为James
)都将重新添加到列表的前面。
A simple solution to keep the position of the first element:保留第一个元素的 position 的简单解决方案:
If the "first insrertion" is not the first element - elements can be inserted in arbitrary positions after all - then a more complex logic is needed.如果“第一个插入”不是第一个元素 - 毕竟元素可以插入到任意位置 - 那么需要更复杂的逻辑。
Unfotunately, there appears to not exist a general sorting algorithm for sublists in the standard library.不幸的是,标准库中似乎不存在用于子列表的通用排序算法。
Use a custom comparator, that places James
before all others:使用自定义比较器,将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;
}
You need to take care of the a==b
case to have a strict weak ordering ( James < James
must return false
).您需要注意a==b
的情况以进行严格的弱排序( James < James
必须返回false
)。 Then James
comes before all others, all other come after James
and otherwise you simply compare the two elements.然后James
在所有其他人之前,所有其他人都在James
之后,否则您只需比较这两个元素。
Note that if there is more than one James
in the list they will both placed in front by this comparsion, so it isn't exactly doing what you asked for.请注意,如果列表中有多个James
,则通过此比较,它们都将排在前面,因此它并没有完全按照您的要求进行。
auto first = newList.front();
newList.sort();
cout<<first<<" ";
for(auto it :newList)
cout<<it<<" ";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.