Qual é a diferença entre std :: lower_bound e std :: upper_bound?

Sep 25 2020

O código abaixo não é compilado com MSVC2017 e GCC11:

#include <deque>
#include <chrono>
#include <algorithm>

using Clock = std::chrono::system_clock;
using TimePoint = std::chrono::time_point<Clock>;

struct PricePoint
{
    TimePoint dt;
    double buy;
    double sell;
};

inline bool operator < (const TimePoint & dt, const PricePoint & a)
{
    return a.dt < dt;
}

int main()
{
    std::deque<PricePoint> priceSequence;
    const auto begin = std::lower_bound(priceSequence.begin(), priceSequence.end(), Clock::now());
    return 0;
}

Mas se eu substituir std::lower_boundpor std::upper_boundele começa a compilar. Qual é a diferença?

Respostas

9 NathanCooper Sep 25 2020 at 03:45

erro: nenhuma correspondência para 'operador <'

Esse tipo de erro sugere que algum código de modelo está tentando usar um operador que você não definiu.

lower_bounde upper_boundfazer comparações opostas. < (const TimePoint & dt, const PricePoint & a)é bom para upper_bound, mas lower_boundprecisa que você defina isto:

inline bool operator < (const PricePoint & a, const TimePoint & dt)
{
    return dt < a.dt;
}