0

我直接从我正在处理的一些代码中提取了这个小片段:

KeyIter it = timeline_.lowerBound( frame );
if ( timeline_.isKeyAtFrame( frame ) ) {
    ++it;
}

KeyIter it1 = it - 1;
cout << "dist1: " << std::distance( timeline_.begin(), it1 ) << endl;
while ( ignore.contains( it1.key() ) ) {
    cout << "dist2: " << std::distance( timeline_.begin(), it1 - 1 ) << endl;
    if ( std::distance( timeline_.begin(), --it1 ) < 0 ) {
        break;
    }
}
cout << "dist3: " << std::distance( timeline_.begin(), it1 ) << endl;

它给出了这个输出:

dist1: 0
dist2: 2
dist3: 2

ignore是一个QSet<int>并且it1是一个迭代器timeline_(它是一个键为 的映射类型int)。如您所见it1,从头开始(这是正确的),然后控制进入 while 循环,在该循环中迭代器向后移动一个;但是 std::distance 不是 -1,而是 2!中间发生的所有事情都是密钥的副本用于检查是否QSet包含相同的int.

使用调试器,我可以确认timeline_两个输出之间没有变化dist#(无论如何,此时代码中只有一个线程正在运行)。

谁能看到为什么std::distance要给出这个输出?

4

1 回答 1

1

I'm not sure about Qt's behavior on this, but in standard library containers, aquiring an iterator outside the range [container.begin(),container.end()] is undefined behavior. I would assume it's the same in Qt, though I'm not sure. However, even if it's not, the behavior of std::distance on non-random access iterators is to count the number of increments required to get from the first iterator to the last, so this:

std::distance(x,y)

where y precedes x, is undefined behavior.

于 2012-07-04T18:09:22.973 回答