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

Viewed 129

Suppose I'm trying to insert random stuff on a list in CPP using include list,

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?

3 Answers

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.

A simple solution to keep the position of the first element:

  • Store iterator to first element
  • Sort the list
  • Splice the element from the stored iterator back to beginning

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:

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). Then James comes before all others, all other come after James and otherwise you simply compare the two elements.

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.

Related