时间:2017-09-13 02:29:53

标签: c++ vector stl

我想在事件数据库中搜索并检查时间t之前的直接事件是什么,以及时间t之后的直接事件是什么。如果事件恰好发生在时间t,我希望前后两者相等。如果给定时间在所有数据库事件之前或之后,那么必须为之前和之后给出最极端的事件。这是代码:

// 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

1 个答案:

答案 0 :(得分:0)

lower_bound将返回大于或等于搜索项的第一个元素。在这种情况下,这是元素6.0。

upper_bound将返回第一个更大但等于搜索项的元素。在这种情况下,它也是元素6.0。

要在要搜索的数字之前获取元素,需要显式递减从lower_bound返回的迭代器。为了防止未定义的行为,您首先需要确保它不在begin()

lower_boundupper_bound视为返回该项目放置在已排序数组中的范围。如果序列中没有出现搜索项,它们将始终返回相同的迭代器。