为什么我不能递增 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
中的元素键。
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?