2012-10-27 106 views
1

我有两个std::vector<string>'s都与在矢量A映射到数量和向量B映射到标题ISO 8601个时间戳C++

A映射与

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

B映射与

ISO 8601点的时间戳
map<string,string> Map2; //<headline,timestamp> 

然后我的第三个地图,从标题去命名

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

本质上我想要做的是获得矢量A映射到矢量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 

是什么矢量地图以向量B的最佳方法有它的?

我最好的方法的两个猜测是将矢量B的第二个下舍入,或者采取某种加权平均值之前和之后,即2012-02-25 06:09:002012-02-25 06:10:00.什么是最好的方法,我该如何实现它?

+0

只需比较最初的部分,直至包括分钟。 –

+0

@KerrekSB会喜欢将秒数舍入到00,我该怎么做? – pyCthon

+0

你的矢量的类型是什么? –

回答

3

首先,你应该让自己的比较仿函数只有字符串比较最新的,即前十六位:

#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;}); 
+0

@pyCthon:噢,对不起,'find'并没有很好的工作方式我portayed它。它需要自己的,特殊的谓词,它应该是'find_if'。 –

+0

http:// pastebin。com/445H6nwz这里的错误和啊,我会尝试find_if现在谢谢! – pyCthon