sort method of a multimap
-
Is there a way to guarantee that the values inside a multimap are sorted in a certain way? I don't mean just sorting the keys, but values mapped to the same key also sorted by a functor (function object) or anything else? Even though I can retrieve the value_comp functor, I cannot set it because it's defined within the multimap class. This default value_comp just sorts the keys. What I really want is that equal_range returns iterators to sorted values according to my compare functor, but I couldn't find a way to accomplish this. The the values returned by the iterators aren't sorted in any special way that I can contro. Thanks for any help, rod
-
Is there a way to guarantee that the values inside a multimap are sorted in a certain way? I don't mean just sorting the keys, but values mapped to the same key also sorted by a functor (function object) or anything else? Even though I can retrieve the value_comp functor, I cannot set it because it's defined within the multimap class. This default value_comp just sorts the keys. What I really want is that equal_range returns iterators to sorted values according to my compare functor, but I couldn't find a way to accomplish this. The the values returned by the iterators aren't sorted in any special way that I can contro. Thanks for any help, rod
Well, you can have sort of what you're after by using
multiset
instead ofmultimap
like the following: Suppose your multimap is originally defined as:std::multimap<type_a,type_b>
So, define a
struct
holding the two parts of themultimap
:struct pair_ab
{
type_a first; // names of members à la std::pair
type_b second;bool operator<(const pair_ab& x)const
{
if(first<x.first)return true;
if(x.first<first)return false;
return second<x.second;
}
};and replace your
multimap
withstd::multiset<pair_ab>
Now, this
multiset
really behaves as a multimap ontype_a
with the added feature that elements with equivalentfirst
members are further sorted bysecond
. Please report back if this works. Good luck. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo