gpt4 book ai didi

c++ - 在 C++ 中,如何找到最大系统日期?

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:53 24 4
gpt4 key购买 nike

我试图在 cpp 中找到允许的最大系统日期,但找不到执行该操作的函数...

谁能帮帮我?

最佳答案

使用 localtime 功能。将值从 0 传递给它至 numeric_limits<time_t>::max() .对于 Not Acceptable 值,此函数将返回空指针。您可以使用二进制搜索算法更快地找到合适的值:O(log2 N) where N = numeric_limits<time_t>::max() .

以下示例使用了 boost 库,但它仍然与平台无关。如果需要,您可以在没有 STL 或 boost 的情况下实现相同的功能。

#include <iostream>
#include <time.h>
#include <limits>
#include <algorithm>
#include <boost/iterator/counting_iterator.hpp>

using namespace std;
using namespace boost;

bool less_time( time_t val1, time_t val2 )
{
tm* v1 = localtime( &val1 );
tm* v2 = localtime( &val2 );
if ( v1 && v2 ) return false;
if ( !v1 && !v2 ) return false;
if ( v1 && !v2) return true;
return false;
};

int main() {
counting_iterator<time_t> x = upper_bound( counting_iterator<time_t>(0), counting_iterator<time_t>(numeric_limits<time_t>::max()), 0, less_time );
time_t xx = *x;
--xx; // upper_bound gives first invalid value so we use previous one
cout << "Max allowed time is: " << ctime(&xx) << endl;

return 0;
}

关于c++ - 在 C++ 中,如何找到最大系统日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1193303/

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