Asif Azad
Asif Azad

Reputation: 25

Set Iterators in C++

Can iterator be subtracted for set stl in c++? Like it is possible in vector...

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

I am not being able to figure out the reason. Why it is not possible in set??

Upvotes: 1

Views: 1213

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

The iterator of std::set is BidirectionalIterator, which doesn't support operator- between iterators. (The iterator of std::vector is RandomAccessIterator, which supports that.)

You can use std::distance instead. (Note that the complexity is linear for InputIterator including BidirectionalIterator.)

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

Upvotes: 4

Related Questions