ISO 8601时间戳C ++

时间:2012-10-27 18:13:46

标签: c++ c++11

我有两个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>

基本上我想要做的是获取Vector A映射到向量B的时间戳的数据。 我遇到的问题是Vector 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

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

我对最佳方法的两个猜测是围绕向量B的第二个向下,或者在2012-02-25 06:09:002012-02-25 06:10:00.之前和之后采取某种加权平均值。什么是最好的方法和我该如何实现呢?

1 个答案:

答案 0 :(得分:3)

首先,你应该让自己成为一个比较函子,只比较最新的字符串,即前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;} );