Re: Sorting a map by value

From: Richard Herring (junk_at_[127.0.0.1)
Date: 08/25/04


Date: Wed, 25 Aug 2004 12:19:54 +0100

In message <opsc9yjw16jxvii7@localhost.localdomain>, Kevin W.
<contact@in.sig> writes
>>> How do I sort a map by the value, rather than the key?
>>
>> You can't sort maps. They are always automatically sorted by key.
>
>Yes, but I should be able to define the "less than" predicate in the
>constructor,

Yes, and it defines the ordering for the lifetime of the map. Once
established, you can't change it.

>or I should be able to pass a custom predicate into the sort function

No, because there _is_ no standard sort function which can be applied to
maps. std::sort() needs random-access non-const iterators.

>(as I understand it, you *can* sort a map because it is only
>automatically sorted when pairs are added or removed).

No. As Kai-Uwe Bux has pointed out, the key element of each pair is
const. But even if you could rearrange their order, it wouldn't do you
any good, because the key lookup algorithm depends on the elements being
correctly ordered. The next time you tried to access an element by key,
you'd get UB.
>
>What I'm really asking is:
>What are the arguments to this functor (values, pointers or
>references),

The same as to std::less, namely (const reference to) key_type, and it
returns bool. And it must implement a strict weak ordering:

a<b && b<c => a<c;
eq(a,b) && eq(b,c) => eq(a, c) where eq(a, b) means !(a<b) && !(b<a)

>and
>How do I access the value from these arguments?
>
The arguments _are_ the values (or references to them.)

-- 
Richard Herring


Relevant Pages

  • Re: Run-time representation of classes
    ... byte or word maps rather than bits). ... which may hold any number of useful function pointers. ... for the tagged reference would be). ... for simple object types, the GC calls a "mark handler", which is a special ...
    (comp.compilers)
  • Re: Biz Tree Challenge
    ... is a programming technique that involves tables of pointers to ... relational rules make it easier to follow and disect structures. ... OO is generally maps of pointers to maps. ...
    (comp.object)
  • Re: Help with containers, pointers, and threads.
    ... use pointers to elements in maps and vectors. ... As I understand it, the pointers could be invalidated if I had say, a thread, adding items to the map or list in the background right? ... Are the .net collection classes thread safe? ...
    (borland.public.delphi.non-technical)
  • Help with containers, pointers, and threads.
    ... I use pointers to elements in maps and vectors. ... Are the .net collection classes thread safe? ...
    (borland.public.delphi.non-technical)