std::map 用迭代器求距离,程序不会终止

std::map find distance with iterators, program does not terminate

当我编译(g++ -std=c++14 map.cpp)和运行这个程序时,它似乎没有终止。谁能解释为什么?但是,正如我所做的那样, find('a') 而不是 'c' 它给出了零。

#include <iostream>
#include <string>
#include <vector>
#include <map> 
#include <algorithm>
using namespace std; 



int main()
{
    map<char, float> m;
    m['a'] = 3.4;
    m['b'] = 5.3;
    m['c'] = 33.3;
    m['d'] = 43.;

    auto it = m.find( 'c' );
    cout << "distance : " << std::distance( it , m.begin() ) << endl;

}

使用

std::distance( m.begin(), it  )

否则调用

std::distance( it , m.begin() )

具有未定义的行为,因为使用了无效的范围。 C++ 中的范围指定为 [first, last ),其中第一个先于或等于最后一个。在 first 等于 last 的最后一种情况下,范围为空。

来自 C++ 标准(27.4.3 迭代器操作)

4 Effects: If InputIterator meets the requirements of random access iterator, returns (last - first); otherwise, returns the number of increments needed to get from first to last.

std::distance(first,last)first 开始 运行 并推进迭代器直到到达 last。在您的情况下,这永远不会发生,因为 it 最有可能在 之后 m.begin() 找到,因此它将永远循环。更改给定 std::distance

的参数顺序

std::distance参考:

The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first.