私はイベントデータベースで検索し、時刻t
の直前のイベントと、時刻t
の直後のイベントを確認します。イベントが正確に時刻t
に発生した場合、前と後の両方がお互いに等しくなるようにしたいと思います。指定された時間がすべてのデータベース・イベントの前後にある場合、最も極端なイベントは前後の両方に指定する必要があります。ここでは、コードです:after_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