c++ - STL map 排序

标签 c++ sorting map stl

更新:我遵循了 John 的指导并修改了他的代码,通过创建比较器函数并将其插入到 STL 映射中的比较参数来解决我的问题。由于我的字符串日期严格按照显示的格式,使用 substr 就可以了。我的输出和代码如下供您引用。

Date            Total Sales
01JAN1900       $4
20JAN1902       $40
18NOV1912       $2500
19NOV1912       $2500
19OCT1923       $25
01JAN1991       $22
15NOV1991       $300
Grand Total:    $5391


 struct CompareDates 
:
  public std::binary_function <bool, std::string, std::string>
{
  bool operator() (const std::string& lhs, const std::string& rhs)
  {


     if(lhs.substr(5,4) < rhs.substr(5,4))
     {
         return true;

     }
     else if (lhs.substr(5,4) == rhs.substr(5,4) && lhs.substr(2,3) < rhs.substr(2,3))
     {
         return true;
     }
     else if (lhs.substr(5,4) == rhs.substr(5,4) && lhs.substr(2,3) == rhs.substr(2,3) && lhs.substr(0,2) < rhs.substr(0,2))
     {
         return true;

     }
     else
     {
         return false;
     }


  }
};

map<string, double,CompareDates> dailyDatePrices;

初始问题:我需要将原始数据整理成每日报告格式。因此,我使用 STL map 将日期存储为键,将商品价格存储为值。根据我的阅读,STL map 是自动排序的。但是我不希望它按 map 排序,因为它会生成下面所述的不需要的当前报告输出。我想根据字符串日期(最早到最新)进行排序,并希望它是那种确切的格式。在使用 map 之前,我已经使用 vector 和函数比较器对日期进行排序。有什么办法去做吗?谢谢!

Raw Data
STRAW:10:15NOV1991
TOY:10:15NOV1991
BARLEY:5:01OCT1992

Undesired Current Report Output
01OCT1992 5
15NOV1991 20

Expected Report Output
15NOV1991 20
01OCT1992 5

最佳答案

std::map 已排序。无法构建未排序的 map

问题不在于 map 已排序。问题在于您的键是如何设计的。

您说过您的 key 是一个日期,但实际上它是一个字符串map 如何知道 string 中的数据实际上是一个日期,并且它应该以某种方式先按年、月、日排序?它不能。你必须告诉它这样做。

将您的键更改为这种格式的字符串:

YYYYMMDD

其中 YMD 都是数字。不要尝试对 11 月使用 NOV - 请改用 11

您也可以使用 unsigned long 作为 key 而不是 string。这将使比较更快,但计算值有点棘手。


如果您必须坚持键的原始格式,那么您需要做一些工作。 map 根据 map 的比较器 进行排序,它被指定为它的 template parameters 之一。 :

[C++03范例]

struct CompareDates 
:
  public std::binary_function <bool, std::string, std::string>
{
  bool operator() (const std::string& lhs, const std::string& rhs)
  {
    // return true if lhs < rhs
    // return false otherwise

    // step 1:  compare years.  if lhs.year < rhs.year, return true.  else, continue
    // step 2: compare months.  if lhs.month < rhs.month, return true.  else, continue.
    //    note:  don't just compare the strings, else "AUG" < "JAN" etc
    // step 3: compare days.  if lhs.day < rhs.day, return true.  else, return false.
  }
};

由于这似乎是家庭作业,所以我会让您填写上面缺失的部分。 :)

使用此比较器来比较键,您可以实例化一个自动执行正确排序的映射:

std::map <Key, Value, CompareDates> myMap;

关于c++ - STL map 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096292/

相关文章:

c - 如何在程序崩溃前检测文本文件是否损坏?

c++ - Directdraw:旋转视频流

C++ 11查找类型是否具有成员函数或支持运算符的方法?

f# - 是在 F# map 上进行迭代还是设置有序遍历?

c - GSL vector 的k个最大元素

java - 如何对 HashMap<String, Integer[]> 进行排序?

perl - 在 Perl 中使用 map 仅在键存在时进行映射

c++ - 使用 boost::regex_search 忽略大小写

c++ - cpoll_cppsp 框架是否像 Ur/Web 一样类型安全?

python - 为什么这不分配一个副本