Mike Copeland writes:
> 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
It's a straightforward, two-step process.
1) Once a map is contructed, iterate through the map, putting a pointer to
each element in a std::vector<CSTYPE *>. Use
std::vector::reserve(map.size()) to preallocate the vector, for maximum
efficiency.
2) Use std::sort() to sort this vector, and provide a custom comparison
function, that uses csKey to order pointers according to csKey
Then, just iterate through the vector.
If you also wish to retrieve the std::string key, then this is the same
process, except using std::vector<std::pair<std::string, CSTYPE> >, since
you'll be storing pointers to the key+data pair.