Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial sort of std::list

Tags:

c++

stl

I have a linked list that I want to sort part of, eg:

std::sort(someIterator, otherIterator, predicate);

std::sort requires random-access iterators so this approach doesn't work. There is a specialisation std::list::sort, but that can only sort the entire list. I don't think I have enough access to the list members to write something myself.

Is there a way to do this without changing to, say, vector?

like image 900
Peter Avatar asked Oct 19 '08 22:10

Peter


People also ask

Can you use std::sort with a list?

std::sort requires random access iterators and so cannot be used with list .

What is partial sort in C++?

C++ Algorithm partial_sort() function is used to rearrange the elements in the range[first, last), in such a way that the elements between the first and middle will be sorted and the elements between the middle and last will be in an unspecified order.

Is std::list sort () stable?

Yes, std::list<>::sort is guaranteed to be stable.

Why does std::list need a special sort method?

std::sort is a generic algorithm that's supposed to work for anything that provides iterators. However, it really expects a random access iterator to sort efficiently. std::list , being a linked list, cannot provide random access to its elements efficiently. That's why it provides its own specialized sort algorithm.


2 Answers

How about unhooking the part of the list that you want sorted, into a standalone list, then use the specialized list sort, then hook it back into the original list?

like image 68
EvilTeach Avatar answered Nov 05 '22 18:11

EvilTeach


Yes, but you will have to use a merge sort.

like image 29
Leon Timmermans Avatar answered Nov 05 '22 19:11

Leon Timmermans