【问题标题】:"No match for operator-" error on simple iterator difference简单迭代器差异上的“与运算符不匹配”错误
【发布时间】:2015-06-28 03:28:08
【问题描述】:

这是我的代码:

#include <set>
#include <iostream>
using namespace std;

int main(){
    set<int> st;
    st.insert(1);
    int x = st.find(1) - st.begin();

    return 0;
}

我收到error: no match for 'operator-' in 'st.std::set&lt;_Key, _Compare, _Alloc&gt;::find [with _Key = int, _Compare = std::less&lt;int&gt;, _Alloc = std::allocator&lt;int&gt;](((const int&amp;)((const int*)(&amp;1)))) - st.std::set&lt;_Key, _Compare, _Alloc&gt;::begin [with _Key = int, _Compare = std::less&lt;int&gt;, _Alloc = std::allocator&lt;int&gt;]()'

我无法弄清楚迭代器差异是如何突然停止工作的!我在这里遗漏了什么吗?

【问题讨论】:

    标签: c++ c++11 iterator c++14 const-iterator


    【解决方案1】:

    由于无法在std::set 上有效地实施此操作,因此未提供。 std::set 提供(Constant) Bidirectional Iterators,可以在任一方向移动,但不能跳跃任意距离,就像std::vector 提供的随机访问迭代器一样。可以看到迭代器概念的层次结构here

    改为使用std::distance 函数,但请注意,对于这种情况,这是一个O(n) 操作,必须遍历两个迭代器之间的每一步,因此在大型std::set 上使用它时要小心s、std::lists 等

    【讨论】:

      【解决方案2】:

      std::set 迭代器是 BidirectionalIterators,而不是 RandomAccessIterators。前者不定义operator-。使用std::distance 计算迭代器之间的差异。

      #include <iterator>
      // ...
      auto x = std::distance(st.begin(), st.find(1));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 2017-08-10
        • 2013-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-25
        相关资源
        最近更新 更多