首页 > 解决方案 > std::lower_bound 和 std::upper_bound 有什么区别?

问题描述

下面的代码不能同时使用 MSVC2017 和 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;
}

但是如果我用它替换std::lower_boundstd::upper_bound就会开始编译。有什么区别?

标签: c++

解决方案


错误:'operator<' 不匹配

这种错误表明某些模板代码正在尝试使用您尚未定义的运算符。

lower_boundupper_bound进行相反的比较。< (const TimePoint & dt, const PricePoint & a)很好upper_bound,但lower_bound需要你定义这个:

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

推荐阅读