“No match for operator-” error on simple iterator difference

不想你离开。 提交于 2019-12-22 00:42:05

问题


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?


回答1:


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.




回答2:


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));


来源:https://stackoverflow.com/questions/29764251/no-match-for-operator-error-on-simple-iterator-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!