2012-03-06 121 views
3

我有一个QMultiMap<QDateTime, SomeOwnDataType>我想从中检索具有特定时间戳的所有值。这是我做的:为什么QMultiMap的查找操作无法按预期工作?

QMap<QDateTime, Appointment>::iterator it = _reminders.find(now); 

其中now迪6.地铁12点07分00秒2012的值。这是我的循环状态:

while (it != _reminders.end() && it.key() == now) { 

这是_reminders对象的状态:

Debug

出乎我的意料,循环被完全忽略。怎么来的?

+0

是“它”指向“_reminders.end()”后查找或有效的项目? – Koying 2012-03-06 12:17:39

+0

在进入循环之前,我检查了'it == _reminders.end()'的条件。这是真的,这就是为什么循环从未被执行。但为什么? “QDateTime”的比较运算符可以与此有关吗? – Pieter 2012-03-06 12:42:45

回答

4

我认为,问题是两个时间戳是不相等的。如果你检查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) { 
+0

D'oh ...我没有想到检查msec组件,因为我没有使用它们。我将通过在所有时间戳上将毫秒组件设置为0来解决此问题。感谢您的解释! – Pieter 2012-03-06 13:18:57

+0

不客气 – pnezis 2012-03-06 13:20:18

0

如何初始化now

QDateTime上升到毫秒,所以,而实际上的值是不同toString()可以显示相同的值... 除非在某个时刻的关键_reminders [0]设置为now的价值,他们将不同。

如果你正在构建一个日历应用程序,你可以使用一个QString为重点,以你的QMultiMap,与值是的QDateTime::toString()输出(取决于您愿意精度(日,小时,分钟的格式。 ..)

相关问题