为什么 std::distance 对 unordered_map 的迭代器不起作用?

Why does std::distance doesn't work on iterator of unordered_map?

我有这个代码:

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

int main()
{
    unordered_map<int, int> umap;
    unordered_map<int, int>::iterator itr1, itr2;
    itr1 = umap.begin();
    itr2 = std::next(itr1, 3);
    cout << distance(itr2, itr1);
    return 0;
}

编译正常。但在执行时会产生 Segmentation fault

为什么我找不到迭代器之间的距离?

std::next(itr1, 3) 的结果超出了 umap.end() 并且是段错误的来源。 umap.end()umap.begin() 的更多内容将因 unordered_map 的内容而失效。这可行,但无论如何都不允许使用 std::distance

umap[0] = 3;
umap[1] = 4;
umap[2] = 5;
umap[3] = 5;
itr1 = umap.begin();
itr2 = std::next(itr1, 3);

unordered_map 在无序容器中,没有 RandomAccessIterator 并且 std::distance 不能在它的迭代器上使用。

您的代码有未定义的行为。

  1. umap 为空,则 std::next(itr1, 3) returns 为无效迭代器。

  2. 更改传递给 std::distance 的参数的顺序。

InputIt must meet the requirements of LegacyInputIterator. The operation is more efficient if InputIt additionally meets the requirements of LegacyRandomAccessIterator

If InputIt is not LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. If InputIt is LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first and first is not reachable from last.

例如

unordered_map<int, int> umap { {1,1}, {2,2}, {3,3} };
unordered_map<int, int>::iterator itr1, itr2;
itr1 = umap.begin();
itr2 = std::next(itr1, 3);
cout << distance(itr1, itr2);

LIVE