让年龄过时的结构
Get age out of date structure
我正在编写一个程序,其中我有一些竞争对手,这些竞争对手是由结构定义的。我还有一个date
结构。
struct date{ int d; int m; int y;};
我必须按竞争对手的年龄对他们进行排序,我不知道如何获得竞争对手的年龄,进行比较。
我也试过这个:
void age(tekmovalec comp){
#define _CRT_SECURE_NO_WARNINGS
time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);
int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900;
int age1, age2;
if(comp.rojDat.m > month){
age1=year-comp.rojDat.y-1;
age2=(12-month) + comp.rojDat.m;
}else{
age1=year-comp.rojDat.y;
age2=12-comp.rojDat.m;
}
int age3 = age1*12 + age2;
comp.age=age3;
}
但它返回错误,指出localtime
不安全。
由于您想按日期排序,您可能需要查看 std::sort。为了进行比较,您需要编写一个函数组合来比较 2 个竞争对手(您只需要使用天、月和年之间的基本比较来比较他们的年龄(。
bool comp(competitor a, competitor b){
if(a.age.y < b.age.y)
return true;
else if(a.age.y == b.age.y && a.age.m < b.age.m)
return true;
else if(a.age.y == b.age.y && a.age.m == b.age.m && a.age.d < b.age.d)
return true;
else
return false;
}
请注意,这不是最好的实现(实际上它很混乱(,但它的目的是给你一个提示,而不是按原样使用。
实现此目的的另一种方法是为竞争对手重载比较运算符。
不需要localtime
.你不需要年龄;你需要的是一种比较年龄的方法。要确定我们谁年纪大,我们不需要知道这是哪一年,我们只需要知道我们谁出生得更早。
编写一个比较两个生日的函数:
bool operator<(const date &A, const date &B)
{
...
}
然后使用它来构建一个比较两个竞争对手的函数,然后使用它来构建一个对竞争对手进行排序的函数。
而不是
可能导致问题(不是线程安全(的localtime()
,您可以使用不应有警告的localtime_r()
:
struct tm *localtime_r(const time_t *restrict timer, struct tm *restrict result);
struct tm mytime; // use this instead of aTime
localtime_r(&theTime, &myTime)
int day = myTime.tm_mday;
int month = myTime.tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int year = myTime.tm_year + 1900;
这也可能是localtime_s()
我猜你正在使用Visual Studio。 _CRT_SECURE_NO_WARNINGS
需要是一个预处理器定义(即在任何#include
或代码之前看到(
右键单击项目,获取"属性"菜单,找到C/C++
预处理器定义并将其放入。为了实际比较时间,如果您在将dat
结构转换为tm
后使用mktime
可能会更容易,但如果有人在 1970 年之前出生,您将遇到麻烦。看这里
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- 让年龄过时的结构