让年龄过时的结构

Get age out of date structure

本文关键字:结构 过时      更新时间:2023-10-16

我正在编写一个程序,其中我有一些竞争对手,这些竞争对手是由结构定义的。我还有一个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 年之前出生,您将遇到麻烦。看这里