我想在事件數據庫中搜索並檢查什麼是時間t
之前的即時事件,以及什麼是時間t
之後的直接事件。如果事件發生在t
時間,我希望前後兩者相等。如果給定時間在所有數據庫事件之前或之後,那麼必須在前後都給出最極端的事件。下面是代碼:lower_bound和upper_bound之後和之前
// g++ -std=c++11 test2.cpp -Wfatal-errors
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Event
{
double event_time;
std::string info;
};
bool operator< (const Event &e1,double rhs_time)
{
return e1.event_time<rhs_time;
}
bool operator< (double lhs_time,const Event &e2)
{
return lhs_time<e2.event_time;
}
int main()
{
std::vector<Event> events=
{
{0.0, "Player 1 built a village"},
{2.0, "Player 2 relocated"},
{2.5, "Player 2 attacked plyer 3"},
{4.0, "Player 4 built walls"},
{6.0, "Player 3 left the game"},
{7.0, "Player 2 built a village"},
};
std::vector<Event>::iterator before,after;
double search_time=4.5;
before=std::lower_bound (events.begin(), events.end(), search_time);
after= std::upper_bound (events.begin(), events.end(), search_time);
std::cout<<"What happened before and after "<<search_time<<"?"<<std::endl;
std::cout
<<"before: @"<<(before->event_time)
<<", "<<(before->info)<<std::endl;
std::cout
<<"after: @"<<(after->event_time)
<<", "<<(after->info)<<std::endl;
return 0;
}
,其結果是
What happened before and after 4.5?
before: @6, Player 3 left the game
after: @6, Player 3 left the game
雖然我期待:
What happened before and after 4.5?
before: @4, Player 4 built walls
after: @6, Player 3 left the game
矢量進行排序。
我該如何解決這個問題?
(wandbox)
使用浮點數作爲索引時要小心,您可能會遇到浮點不準確的問題。你在這裏發佈的每個以.0或.5結尾的數字的例子都不會有這個問題,但是這很容易改變。 –
@MarkRansom,謝謝你提到這一點。我完全意識到這一點。這是一個MWE。在實踐中,我將使用數據結構而不是文本信息,並使用插值。因此,我並不擔心這一點。 – ar2015