排序值C++映射具有多个键值的数据结构

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

本文关键字:键值 数据结构 C++ 映射 排序      更新时间:2023-10-16

这是我的输入文件的一行的格式:

人口|城市|州|高速公路列表===

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

我需要创建一个具有以下格式的输出文件:

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

===>示例:

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

在这里,人口相同的州应该被分组在一起,必须先按州的字母顺序排序,然后按城市排序。我能够得到正确的格式,但我无法确定使用哪种数据结构来对州和城市进行排序。

我现在有map<int, vector<string> >。关键是种群,其余的是矢量。欢迎提出任何建议。

我根本不会为此使用映射。您可能应该弄清楚数据的每个元素实际需要什么信息,并创建任何需要支持的数据类型。例如

struct State
{
    unsigned int Population;
    std::vector<std::string> Cities;
    std::vector<unsigned int> Highways;
};

然后,您可以解析数据,并创建一个std::vector<State>。使用std::Sort对向量和数据进行适当的排序(您可以使用lambdas,或者在必要时创建比较函数或函子)。