Sorting map<T>?

J

Jeff Dege

Suppose I have a problem for which an associative array is the most
natural fit, but which I need to be able to output in sorted order of the
values.

STL map would seem like a good fit, except that maps are sorted on key,
not value.

I can picture a couple of approaches, but I'm not clear on what would be
cleanest.

Any ideas?
 
J

John Harrison

Jeff said:
Suppose I have a problem for which an associative array is the most
natural fit, but which I need to be able to output in sorted order of the
values.

STL map would seem like a good fit, except that maps are sorted on key,
not value.

I can picture a couple of approaches, but I'm not clear on what would be
cleanest.

Any ideas?

Well I suppose the fancy approach would be to have two sets, each
pointing to common data but with different sorting criteria. That way
you'd have key sorted data for lookup and value sorted data for output.
Wrap it all up in a class so things can't get out of step and away you go.

But most of the time I think I'd just copy to a vector, sort the vector
and then throw the vector away.

john
 
M

Mark P

John said:
> But most of the time I think I'd just copy to a vector, sort the vector
and then throw the vector away.

That would be my suggestion too. The only addition I'd make is that, if
the values are large enough that copying and sorting may be inefficient,
you can make a vector of pointers to the map values and sort that instead.
 
C

Clark Cox

Suppose I have a problem for which an associative array is the most
natural fit, but which I need to be able to output in sorted order of the
values.

STL map would seem like a good fit, except that maps are sorted on key,
not value.

I can picture a couple of approaches, but I'm not clear on what would be
cleanest.

Any ideas?

I would probably do one of the following:

1) Copy the data into a vector and sort it, and output *that*, then
discard the vector when you're done.
2) Copy the data into a set, and output that ... (may be faster or
slower than copying to a vector depending on your data)
3) Maintain a set of map::iterator's that is sorted by data type, but
points into your map.
4) Maintian a second map, that contains the same data, but with the key
and value swapped.

I can imagine myself using any of the above methods depending on
performance and data constraints.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Sorting an STL map 1
sorting map value based 6
Paralle sorting algorithms... 0
map ordering 6
Sort Map on Value 42
STL map and char * problems 3
STL: map vs vector 13
Parallel sorting algorithms... 0

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top