7

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?

Peter
  • 7,216
  • 2
  • 34
  • 46
  • and what is the main reason you're using list instead of vector? In spite of the fact std::vector have to perform move on avg. half elements (eg. when deleting), it is super fast thanks to cache. std::vector beats std::list even in frequent deleting and inserting on rand. pos. You have to have very large number of elements to profit by using list. – relaxxx Apr 27 '12 at 18:24
  • Well honestly I can't remember, since in the three and a half years since I asked I'm pretty sure it got refactored away somehow and I've long since left that job anyway. The point of the question was not so much about efficiency (although there's a fair chance that there was enough data that I wouldn't have wanted to duplicate it all on the fly) but more just curiosity; it seemed strange that I didn't seem to be able to do this partial sort and that there should be some way of achieving it. – Peter Apr 27 '12 at 19:58
  • oh :D my bad... I came across this question through search not through "active questions page" and did not realize that :) I actually thought this is active question. – relaxxx Apr 28 '12 at 13:02

2 Answers2

12

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?

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
2

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

Leon Timmermans
  • 30,029
  • 2
  • 61
  • 110