在 C++ 中设置迭代器

Set Iterators in C++

c++中set stl可以减去iterator吗?就像在向量中是可能的...

int32_t main()
{
    set<int> s = {1, 3, 0, 23};
    vector<int> v = {1, 3, 0, 23};

    int vind = find(v.begin(), v.end(), 1) - v.begin(); //This is ok with no error

    int sind = find(s.begin(), s.end(), 1) - s.begin();  //But this gives error
    cout<<vind <<" " << sind;
    return 0;
}

我无法找出原因。为什么在集合中是不可能的??

std::set的迭代器是BidirectionalIterator, which doesn't support operator- between iterators. (The iterator of std::vector is RandomAccessIterator,支持。)

您可以改用std::distance。 (请注意,包括双向迭代器在内的 InputIterator 的复杂度是线性的。)

int sind = std::distance(s.begin(), find(s.begin(), s.end(), 1));