繁体   English   中英

std::lower_bound 和 std::upper_bound 有什么区别?

[英]What is the difference between std::lower_bound and 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::upper_bound替换std::lower_bound ,它就会开始编译。 有什么不同?

错误:“运算符<”不匹配

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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