1

这是我的代码:

#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<_Key, _Compare, _Alloc>::find [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>](((const int&)((const int*)(&1)))) - st.std::set<_Key, _Compare, _Alloc>::begin [with _Key = int, _Compare = std::less<int>, _Alloc = std::allocator<int>]()'

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

4

2 回答 2

9

由于此操作无法在 a 上有效实现std::set,因此未提供。std::set提供(常量)双向迭代器,可以向任一方向移动,但不能跳跃任意距离,如 提供的随机访问迭代器std::vector您可以在此处查看迭代器概念的层次结构。

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

于 2015-04-21T06:16:19.370 回答
5

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

#include <iterator>
// ...
auto x = std::distance(st.begin(), st.find(1));
于 2015-04-21T06:16:43.593 回答