473,395 Members | 1,581 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Sorting a map by value

How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)

--
Kevin W :-)
Opera/CSS/webdev blog: http://www.exclipy.com/
Using Opera: http://www.opera.com/m2/
Jul 22 '05 #1
7 14065
Kevin W. wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)


You can't sort maps. They are always automatically sorted by key.

Jul 22 '05 #2
On Tue, 24 Aug 2004 07:55:19 GMT, "Kevin W." <co*****@in.sig> wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)


You can't - std::map has an invariant that it is sorted by key. You'll
have to copy into a vector or similar first, or perhaps maintain two
parallel maps (key->value and value->key).

Tom
Jul 22 '05 #3
"Kevin W." <co*****@in.sig> wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)


First start with a test:

int main() {
map< char, int > current;
current['a'] = 5;
current['b'] = 4;
current['c'] = 3;

map< int, char > other = converse_map( current );

map< int, char >::iterator begin( other.begin() );
assert( begin->first == 3 );
assert( begin->second == 'c' );
++begin;
assert( begin->first == 4 );
assert( begin->second == 'b' );
++begin;
assert( begin->first == 5 );
assert( begin->second == 'a' );
cout << "OK";
}

When the above prints "OK" you know you are done. Now write the
'converse_map' function...

map< int, char > converse_map( const map< char, int >& o )
{
map< int, char > result;
for ( map< char, int >::const_iterator begin( o.begin() );
begin != o.end(); ++begin )
result.insert( make_pair( begin->second, begin->first ) );
return result;
}

Then turn it into a template...

template < typename T, typename U >
map< U, T > converse_map( const map< T, U >& o )
{
map< U, T > result;
for ( typename map< T, U >::const_iterator begin( o.begin() );
begin != o.end(); ++begin )
result.insert( make_pair( begin->second, begin->first ) );
return result;
}
Jul 22 '05 #4
tom_usenet ha escrito:
On Tue, 24 Aug 2004 07:55:19 GMT, "Kevin W." <co*****@in.sig> wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)


You can't - std::map has an invariant that it is sorted by key. You'll
have to copy into a vector or similar first, or perhaps maintain two
parallel maps (key->value and value->key).


Boost.MultiIndex (to appear promptly in Boost 1.32, online docs
already available at boost-consulting.com/boost/libs/multi_index) can
be used to construct such a bidirectional map easily. This is shown in one

of the examples at

boost-consulting.com/boost/libs/multi_index/doc/examples.html#example4

Regards,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo

Jul 22 '05 #5
Kevin W. wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)


The map data structure is an association between a key
and a value. The std::map requires that each key be
unique. However, two keys can have the same value.
How will you handle the collating of pairs with
the same value but different keys?

If you _really_ want to sort the map, what you are
saying is that you want the data in the map to
be sorted by value. Easy, copy the data into
a new std::multi_map but swap the key with the
value before placing into the multimap. Or
you could use a list, or vector and a sort
function.

Search the newsgroup for "view pattern". For
a hint on how to make a "view" of the data
without altering where the data is stored.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #6
Kevin W. wrote:
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, this less_than predicate will be used to compare the keys.
or I should be able to pass a custom predicate into the sort
function (as I understand it, you *can* sort a map because it is only
automatically sorted when pairs are added or removed).


The std::map<Key,T> container is a sequence of pairs. The type of these
pairs is std::pair<const Key, T >. Please note the *const*. Because of this
'const', you cannot change the keys once they are inserted into the
sequence. It follows that you cannot feed a segment of a map into
std::sort(). The swaps that std::sort() wants to perform are barred by
constness of keys.
Best

Kai-Uwe Bux
Jul 22 '05 #7
In message <op**************@localhost.localdomain>, Kevin W.
<co*****@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
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys()...
12
by: pmud | last post by:
Hi, I am using teh following code for sorting the data grid but it doesnt work. I have set the auto generate columns to false. & set the sort expression for each field as the anme of that...
4
by: John Bullock | last post by:
Hello, I am at wit's end with an array sorting problem. I have a simple table-sorting function which must, at times, sort on columns that include entries with nothing but a space (@nbsp;). I...
18
by: Scott | last post by:
I have a collection where the items in the collection are dates. I want to iterate over the collection and build a value list string for the rowsource of a listbox. The dates in the collection are...
19
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to...
7
by: Kamal | last post by:
Hello all, I have a very simple html table with collapsible rows and sorting capabilities. The collapsible row is hidden with css rule (display:none). When one clicks in the left of the...
1
by: Ahmed Yasser | last post by:
Hi all, i have a problem with the datagridview sorting, the problem is a bit complicated so i hope i can describe in the following steps: 1. i have a datagridview with two columns...
1
by: castron | last post by:
Hello All, I have a grid view that allows sorting, paging, editing, etc. Under On Load event, if I check: if(!IsPostBack){ DisplayData(); }, the Edit portion works fine. However, the Sorting...
5
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The...
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.