I want to sort elements in map container using only values not key. how to do it? I know that map can sort by key value, but how to do vice versa. I found same question in stackoverfrlow. I like this solution. However I want clarify what does it mean "dump in pair<K,V>
". I don't want create special structure for that, it is not elegant. how do you implements this solution?
Asked
Active
Viewed 1.2k times
4
-
1the aim of map is to sort by the key... you can not sort the two in the same time... (i do not downvote :) ) – Hicham Dec 27 '11 at 03:37
-
What do you mean by "sort map container"? Actually sort the elements, or reverse the role of key and value in retrieval? By "dumping in `pair`", do you mean inserting a new key/value pair from the `pair`? (mind, I wasn't the downvoter) – ssube Dec 27 '11 at 03:38
-
3I downvoted your question because it is not clear what the problem is. What is "not elegant"? The question you linked to had three answers with three alternative solutions. – Oliver Charlesworth Dec 27 '11 at 03:38
-
1You need to explain further the parts of the link that are confusing or not applicable to your situation. – Mark Ransom Dec 27 '11 at 03:39
-
3The question you linked to explains exactly how to do what you're asking. If there's something you don't understand, ask a specific question about that part of it. – Brian Roach Dec 27 '11 at 03:40
-
@OliCharlesworth Ok, I have edited my question. Is it clear now? – ashim Dec 27 '11 at 03:45
-
you cannot sort by value without any additional 'structure'... except if you want to invert key and value – Hicham Dec 27 '11 at 03:47
-
1@michael You should look at [boost::bimap](http://www.boost.org/doc/libs/1_48_0/libs/bimap/doc/html/index.html) – Dec 27 '11 at 04:07
-
If your question about the solution is that simple, then you should just post it as a comment on the answer... – Karl Knechtel Dec 27 '11 at 06:57
-
@KarlKnechtel Then when people will answer me if it was asked last year? – ashim Dec 28 '11 at 04:33
1 Answers
19
In order to dump the information from a std::map into a std::vector, you can use std::vector's constructor that takes two iterators.
std::vector<std::pair<K,V> > myVec(myMap.begin(), myMap.end());
You would then sort it with:
std::sort(myVec.begin(),myVec.end(),&myFunction);
myFunction
would be a function defined with the signature:
bool myFunction(std::pair<K,V> first, std::pair<K,V> second);
Have it return true if you they are in the right order(i.e. first should be before second). Return false when they are in the wrong order(i.e. second should be before first).
Also, you might want to look at boost::bimap, which seems more attuned to your problem.
-
-
but, every time the map changes, you have to do again the same operations with the vector to sort it with its new content ! – Hicham Dec 27 '11 at 04:04
-