我有一个QMultiMap<QDateTime, SomeOwnDataType>,我想从它中检索带有特定时间戳的所有值。我就是这样做的:
QMap<QDateTime, Appointment>::iterator it = _reminders.find(now);其中now的值为di 6. mrt 12:07:00 2012。这是我的循环条件:
while (it != _reminders.end() && it.key() == now) {这是_reminders对象的状态:

与我的预期相反,这个循环被完全跳过了。怎么会这样?
发布于 2012-03-06 12:58:23
我相信问题是这两个时间戳是不相等的。如果您检查==运算符代码QDateTime,您将看到,如果时间和日期相等,则等式仍然有效。
bool QDateTime::operator==(const QDateTime &other) const
{
if (d->spec == other.d->spec && d->utcOffset == other.d->utcOffset)
return d->time == other.d->time && d->date == other.d->date;
else {
QDate date1, date2;
QTime time1, time2;
d->getUTC(date1, time1);
other.d->getUTC(date2, time2);
return time1 == time2 && date1 == date2;
}
}但是时间相等操作符比较毫秒:
bool operator==(const QTime &other) const { return mds == other.mds; }其中mds是以毫秒为单位的时间。在QTime构造函数中,mds计算如下:
mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;如果您只是检查两个时间戳之间的差异是否在限制范围内,则会更安全。例如:
while (it != _reminders.end() && abs(now.msecsTo(it.key())) < aLimitInMsecs) {发布于 2012-03-06 12:58:14
如何初始化now?
QDateTime上升到毫秒,所以toString()可以显示相同的值,而实际上值是不同的。除非在某个时候键_reminders被设置为now的值,否则它们将是不同的。
如果您正在构建日历应用程序,您可以使用QString作为QMultiMap的键,其值是QDateTime::toString()的输出(格式取决于您愿意使用的精度(天、小时、分钟、.)
https://stackoverflow.com/questions/9583017
复制相似问题