gpt4 book ai didi

c++ - 检查 std::chrono 持续时间小于 0 的惯用方法

转载 作者:行者123 更新时间:2023-12-03 06:53:37 33 4
gpt4 key购买 nike

我知道我可以做到这一点

if (timeLeft.count() < 0)
但我想知道什么是最好的方法,因为我也可以这样做:
if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...
注意:我假设两个检查是相同的,但我不是计时专家。
编辑:完整示例:
#include<chrono>
int main(){
const std::chrono::nanoseconds timeLeft(-5);
if(timeLeft<std::chrono::seconds(0)){
return 47;
}
}
编辑 2: std::chrono::seconds(0) 的潜在问题是新手程序员可能会认为它涉及舍入,尽管它没有。

最佳答案

表达这一点的方法之一是使用 std::chrono::duration 文字( https://en.cppreference.com/w/cpp/chrono/duration )。它简短而干净:

#include<chrono>

int main(){
using namespace std::chrono_literals;

const auto timeLeft = -5ns;
if(timeLeft<0s){
return 47;
}
}

关于c++ - 检查 std::chrono 持续时间小于 0 的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64206448/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com