排序存储在向量中的日期(字符串)

时间:2014-01-13 15:48:16

标签: c++

我有一个包含这种格式的日期的矢量,DDMMMYY,例如12Jan14

vector <string> tempDate

当我使用STL排序时,基本上当所有日期都在同一年/月时它将起作用。 01Jan14,05Jan14,11Jan14等但是当我进入02Feb14时,它们都将被搞砸。

sort (tempDate.begin(), tempDate.end()

有谁能告诉我它出了什么问题?

编辑:我尝试使用模板,但它不起作用,因为所有字符串都被“拆分”了。 我在sortDayMonthYear

中做了一些故障排除
template <class T>
bool sortDayMonthYear(T a, T b)
{
   for (int i =0; i < a.size(); i++)
     cout << a.at(i)<< endl;

}

我得到的是这样的东西

0
1
J
A
N
1
4
0
2
J
A
N
1
4

实际上,当我打算做的是将两个字符串传递给模板函数时,使用substr来获取日,月,年,比较并返回true或false。

2 个答案:

答案 0 :(得分:3)

您的谓词应该将两个常量字符串引用作为参数,然后使用它们来决定哪一个比另一个“更小”。

所以:

bool sortDayMonthYear(const std::string& first, const std::string& second)
{
    // Algorithm to find out which string is "lesser" than the other
}

然后在排序时使用该比较器功能:

std::sort(std::begin(tempDate), std::end(tempDate), sortDayMonthYear);

答案 1 :(得分:2)

排序字符串的标准方法是词典(按字母表,对于每个字母,就像在字典中一样)。

因此,您需要的是您自己的比较器。有一个排序版本,其中一个作为第三个参数。参见例如这个问题可以提出想法:Sorting a vector of custom objects