Qual è la differenza tra std :: lower_bound e std :: upper_bound?

Sep 25 2020

Il codice seguente non viene compilato sia con MSVC2017 che con 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;
}

Ma se sostituisco std::lower_boundcon std::upper_boundesso inizia a compilare. Qual è la differenza?

Risposte

9 NathanCooper Sep 25 2020 at 03:45

errore: nessuna corrispondenza per "operatore <"

Questo tipo di errore suggerisce che il codice del modello sta tentando di utilizzare un operatore che non hai definito.

lower_bounde upper_boundfare confronti opposti. < (const TimePoint & dt, const PricePoint & a)va bene per upper_bound, ma è lower_boundnecessario che tu lo definisca:

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