为什么我不能递增 std::unordered_map 迭代器?

Why can't I increment std::unordered_map iterator?

std::unordered_map<int, int> _cache;

std::vector<std::unordered_map<int, int>::iterator> _lruList;

这有效

std::rotate(_lruList.begin(), _lruList.begin() + 1, _lruList.end());

但这不是

std::rotate(_cache.begin(), _cache.begin() + 1, _cache.end()); // error occurs on _cache.begin() + 1 saying "error type"

这对我来说真的没有意义,因为它们都是迭代器,除了一个用于 vector 和一个用于 unordered_map

然后我也试了这个 std::rotate(_cache.begin(), _cache.begin() ++, _cache.end());

但我收到以下错误: _Left: you can't assign to a variable that is const _Right: you can't assign to a variable that is const

unordered_map 迭代器是前向迭代器。这意味着它们一次只能移动一步,只能向前移动,从一个位置到另一个位置需要遍历所有中间位置。因此,前向迭代器不支持 operator+,因为它是一个 O(n) 操作。标准库的作者认为,当人们看到 a + b 时,他们期望它是 O(1),因此如果迭代器类型不能满足该要求,则不应支持该运算符。

vector 迭代器是随机访问的,这意味着它们确实支持 operator+,因为它可以实现为 O(1)。您可以这样做:

std::rotate(_cache.begin(), std::next(_cache.begin()), _cache.end());

除此之外也行不通,因为std::rotate是一个修改操作。并且不能修改unordered_map.

中元素的key