Kod*_*rok 1 c++ iterator const-iterator c++11 c++14
这是我的代码:
#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>]()'.
我无法弄清楚迭代器差异是如何突然停止工作的!我在这里错过了什么吗?
因为该操作不能在a上有效地实现std::set,所以不提供.std::set提供(常量)双向迭代器,可以向任一方向移动,但不能跳过任意距离,如随机访问迭代器提供的std::vector.您可以在此处查看迭代器概念的层次结构.
相反,使用该std::distance函数,但请注意,对于这种情况,这是一个O(n)操作,必须沿着两个迭代器之间的每一步走,所以在大std::sets,std::lists等上使用它时要小心.
std::set迭代器是BidirectionalIterators,而不是RandomAccessIterators.前者没有定义operator-.使用std::distance计算迭代器之间的差异.
#include <iterator>
// ...
auto x = std::distance(st.begin(), st.find(1));