Sorting a map on Non-key Data

M

Mike Copeland

I need to sort a map structure on an element that's not the storage
key. Here's the structure declaration:

struct CSTYPE
{ // City/State Record
string csKey; // City/State "Key"
string csString; // City & State data
} extern workCS;
typedef map<string, CSTYPE> CSINFO;
CSINFO cityStInfo;
map<string, CSTYPE>::iterator csIter;

The element I'm storing the map is csString, but once the map is
constructed I want to sort the structure by csKey. I was hoping that
there's a way to either reconstruct the map data or sort it so that I
could iterate through it in "csKey" order. Any thoughts? TIA
 
A

acehreli

   I need to sort a map structure on an element that's not the storage
key.  Here's the structure declaration:

struct CSTYPE
{                                         // City/State Record
        string csKey;                     // City/State "Key"
        string csString;                  // City & State data}       extern workCS;

typedef map<string, CSTYPE> CSINFO;
        CSINFO cityStInfo;
        map<string, CSTYPE>::iterator csIter;

   The element I'm storing the map is csString, but once the map is
constructed I want to sort the structure by csKey.  I was hoping that
there's a way to either reconstruct the map data or sort it so that I
could iterate through it in "csKey" order.  Any thoughts?  TIA

If the collection is not changing dynamically once it's constructed,
and you will be accessing it many times once it's sorted, then your
best bet is to use std::vector:

vector<CSTYPE> collection;
/* populate the collection here */

std::sort(collection.begin(), collection.end(),
your_sorting_function);

Ali
 

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

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top