如果时间戳不在存储时间戳的地图中,我想在地图中找到最匹配的时间戳,并使用最接近的值作为键。我具有要尝试执行的基本结构设置,但我不确定如何找到最近的时间戳
typedef std::map<std::string,int> Map;
Map::iterator it;
Map my_map;
my_map["2010-01-26 17:02:12"]= 1;
my_map["2010-01-25 08:55:29"]= 2;
my_map["2010-01-24 08:55:29"]= 3;
string timestamp = "2010-01-24 08:55:30"; // would return 3
string timestamp1 = "2010-01-27 01:55:30"; // would return 1
it = my_map.find(timestamp);
if(it == my_map.end()){
//not sure how to approach this
}
更新
我试图避免将相当大的代码库从
std::string
转换为uint64_t
,尽管这会提高性能,但这并不是一个大问题,我无法使用
std::map::lower_bound
或std::map::upper_bound
解决方案这是我对IDE ONE的尝试,
http://ideone.com/MnRLIH
最佳答案
std::map::lower_bound
或std::map::upper_bound
可能会满足您的需求,这两种都是O(log N)复杂性。
另外,强烈考虑将时间戳记存储为uint64_t
而不是字符串。这将大大减少要比较和处理的计算量。
关于c++ - map 上最接近的字符串/时间戳,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14306745/