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

时间:2016-06-19 06:06:34

标签: c++ iterator const increment unordered-map

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

1 个答案:

答案 0 :(得分:3)

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中的元素键。

相关问题