我有两个 std::vector<string>'s
两者都带有 ISO 8601 时间戳,其中 vector A 映射到数字, vector 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 ,从标题到名字
map<string,string> Map3; //<headline,name>
本质上,我要做的是获取 vector A 在 vector B 的时间戳映射到的数据。 我遇到的问题是 vector A 具有以下格式的 iso 时间戳,其中秒数始终为零,
2012-02-25 06:09:00
2012-02-25 06:10:00
vector B 在几秒钟内完成
2012-02-25 06:09:32
2012-02-25 06:09:38
2012-02-25 06:09:51
将 vector A 映射到 vector B 的最佳方式是什么?
我对最佳方法的两个猜测是将 vector B 的第二个向下舍入,或者在前后取某种加权平均值,即 2012-02-25 06:09:00
和 2012-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;
或者你可以制作一个排序的 vector :
#include <vector>
#include <algorithm>
std::vector<std::string> v;
std::sort(v.begin(), v.end(), isotimecomp());
然后你可以对 vector 进行二分查找:
std::string str = "2012-02-25 06:09:00";
auto it = std::lower_bound(v.begin(), v.end(), str, isotimecomp());
或者您可以在 vector 上使用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;} );
关于c++ - ISO 8601 时间戳 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13102820/