问题
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::set
s, std::list
s, 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