“No match for operator-” error on simple iterator

2020-08-01 05:48发布

Here is my code:

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

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

    return 0;
}

I am getting 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>]()'.

I am not able to figure out how did iterator difference stopped working all of a sudden! Am I missing something here?

2条回答
成全新的幸福
2楼-- · 2020-08-01 06:02

std::set iterators are BidirectionalIterators, not RandomAccessIterators. The former do not define operator-. Use std::distance to calculate the difference between the iterators.

#include <iterator>
// ...
auto x = std::distance(st.begin(), st.find(1));
查看更多
Viruses.
3楼-- · 2020-08-01 06:18

Because this operation can't be implemented efficiently on a std::set, it is not provided. std::set provides (Constant) Bidirectional Iterators, that can be moved in either direction, but not jumped arbitrary distances, like the Random Access Iterators provided by std::vector. You can see the hierarchy of iterator concepts here.

Instead, use the std::distance function, but be aware that for this case, this is an O(n) operation, having to walk along every step between the two iterators, so be cautious about using this on large std::sets, std::lists, etc.

查看更多
登录 后发表回答