ISO 8601 timestamps C++

ISO 8601 timestamps C++

本文关键字:C++ timestamps 8601 ISO      更新时间:2023-10-16

我都有两个 std::vector<string>'s,均为ISO 8601时间戳,其中向量a映射到一个数字,向量b映射到标题

a用

映射
 typedef pair<string,string> Key;   //<name,timestamp>
 typedef map< Key, double> Map;     //number
 Map pair_map;

b用

映射
 map<string,string> Map2; //<headline,timestamp>

然后,我有第三张地图,从标题到名称

 map<string,string> Map3; //<headline,name>

从本质上讲,我要做的就是获取向向量B的时间戳记的数据将图向量的数据。我遇到的问题是向量A具有以下格式的ISO时间邮票,其中秒始终为零,

2012-02-25 06:09:00
2012-02-25 06:10:00

向量B与秒

一起使用
2012-02-25 06:09:32
2012-02-25 06:09:38
2012-02-25 06:09:51

将向量A映射到向量B的最佳方法是什么?

我对最佳方法的两个猜测是将矢量B的第二个猜测到围绕第二个向量,或在2012-02-25 06:09:002012-02-25 06:10:00.之前和之后进行某种加权平均水平,什么是最好的方法,我该如何实施?

首先,您应该使自己成为一个比较函数,只能将字符串比较到分钟,即前16位数字:

#include <string>
struct isotimecomp
{
    // models "s1 < s2" for ISO time stamps
    bool operator()(std::string const & s1, std::string const & s2) const
    {
        return s1.compare(0, 16, s2, 0, 16) < 0;
    }
};

现在您可以以任何方式使用它。例如,您可以在时间戳上制作一个关联容器:

#include <map>
std::map<std::string, std::pair<int, std::string>, isotimecomp> timestamp_data;

,也可以做一个分类的向量:

#include <vector>
#include <algorithm>
std::vector<std::string> v;
std::sort(v.begin(), v.end(), isotimecomp());

然后您可以在向量上进行二进制搜索:

std::string str = "2012-02-25 06:09:00";
auto it = std::lower_bound(v.begin(), v.end(), str, isotimecomp());

或者您可以在向量上使用find_if,但是您需要其他谓词:

auto it = std::find_if(v.begin(), v.end(), [&str](std::string const & s) -> bool
                       { return str.compare(0, 16, s, 0, 16) == 0;} );
相关文章: