2

I've got an ordered container (usually std::vector) with objects, say

  1. Banana
  2. Apple
  3. Peach

and above custom order. Now the objects go through some processing, might have been removed from the container and reinserted, resulting in a new ordered container.

I have stored the order (Banana -> 1, Apple -> 2, Peach -> 3) separately and would like to re-establish that particular custom order in the new ordered container.

The objects are already present at this time (i.e. I cannot simply insert in the desired order).

So rather than swapping excessively with some naive algorithm on my own I was wondering if there's some algorithm in the standard library I could employ in a cunning way..?

3
  • Why not leave the objects in the container and copy out of the container? vector returns a reference that you can work on. Commented Jan 12, 2015 at 15:11
  • 6
    Are you looking for something like std::sort(fruits.begin(), fruits.end(), [](const std::string& a, const std::string& b) { return rank[a] < rank[b]; }); where rank is std::map<std::string, int> holding your string-to-rank mapping? Commented Jan 12, 2015 at 15:19
  • @IgorTandetnik Cheers - that did the job.. could have thought of that myself.. Commented Jan 13, 2015 at 6:50

2 Answers 2

1

std::sort is in the standard library AND it's pretty cunning! It can sort by the default < operator (which you could override for your fruit) or you can supply a comparator that's external to your class' implementation.

http://www.cplusplus.com/reference/algorithm/sort/?kw=sort

Sign up to request clarification or add additional context in comments.

2 Comments

(Oh, Igor beat me to it!)
I think the question is, what should be in that operator
1

Well, pretty much what Igor wrote does the job..

std::sort(fruits.begin(), fruits.end(), [&](const std::string& a, const std::string& b) { return rank[a] < rank[b]; } ); 

where rank is std::map<std::string, int> holding the string-to-rank mapping

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.