Search code examples
c++c++11iteratorc++14const-iterator

"No match for operator-" error on simple iterator difference


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?


Solution

  • 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.