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

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

本文关键字:unordered 迭代器 map std 不能 为什么      更新时间:2023-10-16
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中的元素键。