简体   繁体   中英

lower_bound and upper_bound for after and before

I would like to search in an event database and check what is the immediate event before time t and what is the immediate event after time t . If the event happens exactly at time t , I would like the both before and after be equal to each other. If the given time is before or after all database events, then the most extreme event must be given for both before and after. Here is the code:

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

and the result is

What happened before and after 4.5?
before: @6, Player 3 left the game
after: @6, Player 3 left the game

While I was expecting:

What happened before and after 4.5?
before: @4, Player 4 built walls
after: @6, Player 3 left the game

The vector is sorted.

How should I fix this code?

( wandbox )

lower_bound will return the first element that is greater than or equal to the search item. In this case that is element 6.0.

upper_bound will return the first element that is greater but not equal to the search item. In this case that is also element 6.0.

To get the element before the number you're searching for, you need to explicitly decrement the iterator returned from lower_bound . To prevent undefined behavior you will first need to make sure it isn't already at begin() .

Think of lower_bound and upper_bound as returning the range of where that item would be placed in the sorted array. If the search item doesn't occur in the sequence, they will always return the same iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM