简体   繁体   English

为什么我不能增加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;

this works 这很有效

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

but this doesn't 但事实并非如此

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

Which doesn't really make sense to me because they are both iterators except one is for a vector and one is for a unordered_map 这对我来说真的没有意义,因为它们都是迭代器,除了一个用于vector而一个用于unordered_map

Then I also tried this std::rotate(_cache.begin(), _cache.begin() ++, _cache.end()); 然后我也尝试了这个std::rotate(_cache.begin(), _cache.begin() ++, _cache.end());

but I got the following errors: _Left: you can't assign to a variable that is const _Right: you can't assign to a variable that is const 但我得到以下错误: _Left: you can't assign to a variable that is const _Right: you can't assign to a variable that is const

unordered_map iterators are forward iterators. unordered_map迭代器是前向迭代器。 That means they can only move one step at a time, only forward, and getting from one position to another requires traversing all of the intervening positions. 这意味着他们一次只能移动一步,只能向前移动,从一个位置移动到另一个位置需要遍历所有中间位置。 As such, forward iterators do not support operator+ , because it would be an O(n) operation. 因此,前向迭代器不支持operator+ ,因为它将是O(n)操作。 The authors of the standard library felt that when people see a + b , they expect that to be O(1), and so if an iterator type can't meet that requirement, then the operator should not be supported. 标准库的作者认为,当人们看到a + b ,他们希望是O(1),因此如果迭代器类型不能满足该要求,则不应该支持运算符。

vector iterators are random access, which means they do support operator+ , because it can be implemented as O(1). vector迭代器是随机访问,这意味着它们支持operator+ ,因为它可以实现为O(1)。 You can do this instead: 你可以这样做:

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

Except that also won't work, because std::rotate is a modifying operation. 除此之外也不起作用,因为std::rotate是一个修改操作。 And you can't modify the keys of elements in unordered_map . 并且您无法修改unordered_map中元素的键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM