在下面的程序中,我将包含许多不同日期的data
传递给函数GetAvgDayVolm()
,其中的cout
语句然后该函数输出 1
。
但它应该输出超过 1
,因为 data
中有多个不同的日期。尽管程序根本没有进入 if
语句,但看起来 curTime
已更改。你看出什么问题了吗?
long int GetAvgDayVolm(list<struct DataPoint>* data)
{
long long int totalVolm = 0;
long int numOfDays = 1;
struct DataPoint dp = (*data).front();
time_t rawTime2 = dp.timeStamp;
time_t rawTime = 0;
struct tm* curTime = gmtime(&rawTime2);
struct tm* movingTime = new struct tm ();
for(list<struct DataPoint>::iterator it = (*data).begin(); it != (*data).end(); ++it)
{
rawTime = (*it).timeStamp;
movingTime = gmtime(&rawTime);
totalVolm += (*it).volm;
if(curTime->tm_mday != movingTime->tm_mday ||
curTime->tm_mon != movingTime->tm_mon ||
curTime->tm_year != movingTime->tm_year)
{
numOfDays = numOfDays + 1;
curTime = movingTime;
}
}
cout<<numOfDays<<endl;
return 0;
}
最佳答案
在 gmtime 联机帮助页中,注释部分显示:
The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe
因此,在您的代码中,curTime 和 movingTime 指向相同的静态数据区域,您应该使用 gmtime_r 代替,或者先保存结果。
关于c++ - 包含许多被认为只有一个成员的结构的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36145459/