c++ - 不匹配 ‘operator+=’ aka std::_Rb_tree_const_iterator std::map

标签 c++ c++11

<分区>

我有一个名为 assets 的 map 从 const 函数返回,我使用 const_iterator 来获取映射的子集,如下所示:

std::map<int, Asset>::const_iterator start = assets.begin();
start += 5;
......

但我得到错误:error: no match for ‘operator+=’ (operand types are ‘std::map<int, Asset>::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const int, Asset> >}’ and ‘int’)

最佳答案

这是因为 std::map 迭代器是双向迭代器,而不是 RandomAccessIterators - 因此支持 operator++operator-- 但不支持 operator+=operator-=

改为使用 std::advance(start, 5)(请记住,这将导致重复调用 operator++)。

关于c++ - 不匹配 ‘operator+=’ aka std::_Rb_tree_const_iterator std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997584/

相关文章:

python - 如何捕获包含在 boost python 模块中的 C++ 代码中抛出的 Python 异常

c++ - friend 模板特化声明中不允许使用 Consexpr?

c++ - 指针中的 constexpr 有区别吗

c++ - 使用智能指针的访问冲突

C++ 类错误

c++ - 推力结构 vector 的迭代器

c++ - 为什么以及何时执行重载构造函数?

c++ - weak_ptr vs unique_ptr 引用 - 将接口(interface)实现传递给其他对象

c++ - enable_if 似乎在类外工作但不在类内

c++ - 通过间接示例解释 C++ 可变性