简体   繁体   中英

Sorting values C++ map data structure with many values for a key

This is the format of a line my input file:

Population|City|State|ListOfHighways ==>

6|Oklahoma City|Oklahoma|I-35;I-44;I-40 6|Boston|Massachusetts|I-90;I-93 8|Columbus|Ohio|I-70;I-71

I need to create an output file with this following format:

Population (newline) City, State Interstates: Comma-separated list of interstates, sorted by interstate number ascending (newline)

==> Example:

6

Boston, Massachusetts
Interstates: I-90, I-93

Oklahoma City, Oklahoma
Interstates: I-35, I-40, I-44

8

Columbus, Ohio
Interstates: I-70, I-71

Here, the states having the same population should be grouped together and they have to be sorted alphabetically by state first and then by cities. I was able to get the format right, but I am not able to figure out which data structure to use to sort the states and then the cities.

I have map<int, vector<string> > now. key is the population and the rest is the vector. Any suggestions are welcome.

I wouldn't use a map for this at all. You should probably figure out what information you actually need for each element of the data, and create whatever data types you need to support that. Eg

struct State
{
    unsigned int Population;

    std::vector<std::string> Cities;

    std::vector<unsigned int> Highways;
};

You can then parse in your data, and create a std::vector<State> . Sort the vector and data as appropriate using std::sort (you can use lambdas, or create comparison functions or functors if necessary).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM