简体   繁体   English

我应该使用哪种数据类型作为 STL 映射的键?

[英]Which data type should I use as the key for STL map?

I'm creating a program that reads some records from a .csv file and stores it in a map.我正在创建一个从 .csv 文件读取一些记录并将其存储在地图中的程序。 My key is supposed to have two attributes, year and month.我的密钥应该有两个属性,年和月。 But in some cases, I'm asked to print the data of the entire year and in that case, I will not have the option to enter the month (ie month=0).但在某些情况下,我被要求打印全年的数据,在这种情况下,我将无法选择输入月份(即月份=0)。 So which data type should be best in this case?那么在这种情况下哪种数据类型最好? At first, I thought of integers but, it would not work if I'm asked to print the details of the entire year.起初,我想到了整数,但是如果我被要求打印全年的详细信息,它就行不通了。 I think probably using a user-defined type object would work, however, I'm a little confused about iterating the map.我认为使用用户定义的类型对象可能会起作用,但是,我对迭代地图有点困惑。

Sounds like your Month and Year are two independent keys, and that sometimes you are looking for non-unique results (eg year specified, month not specified).听起来您的MonthYear是两个独立的键,有时您正在寻找非唯一结果(例如指定年份,未指定月份)。 Simple solution is to store your records in std::map<Year, std::map<Month, std::vector<Records> > my_data ;简单的解决方案是将您的记录存储在std::map<Year, std::map<Month, std::vector<Records> > my_data Then然后

  • to get the records from the particular Year , you can iterate through the result of my_data[Year("2020")]要获取特定Year的记录,您可以遍历my_data[Year("2020")]
  • to get the records from the particular Month (regardless the Year ), for (const auto& el: my_data) doSomething(el.second[Month("September")]);获取特定Month (无论Year )的记录, for (const auto& el: my_data) doSomething(el.second[Month("September")]); = to get the results from the particular Year and Month my_data[Year("2010")][Month("December")] = 获取特定YearMonth的结果my_data[Year("2010")][Month("December")]

Since C++20 you can use year and month from the standard C++ library;从 C++20 开始,您可以使用标准 C++ 库中的 Before that you can just define Year and Month structures and provide "less than" operator.在此之前,您可以只定义YearMonth结构并提供“小于”运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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