【问题标题】:no match for ‘operator+=’ aka std::_Rb_tree_const_iterator std::map [duplicate]'operator+=' aka std::_Rb_tree_const_iterator std::map [重复] 不匹配
【发布时间】:2016-08-28 02:41:26
【问题描述】:

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

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

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

【问题讨论】:

  • 重复的大约是std::list,但问题完全一样:std::map 有双向运算符,不支持这种类型的算术运算。您需要一次增加一个步骤。

标签: c++ c++11


【解决方案1】:

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

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

【讨论】:

  • 请注意,如果 std::advance 是随机访问迭代器,它将调用 operator+=。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 2018-12-20
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多