2012-10-27 102 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