BratBart
BratBart

Reputation: 407

Error on `it-1` with set iterator

In following code I can not recognize difference between --it, and it-1. Also is words.end() value is out of set range?

#include <iostream>
#include<set>

using namespace std;

int main()
{
    set<string> words;
    words.insert("test");
    words.insert("crack");
    words.insert("zluffy");
    set<string>::iterator it=words.end();
    cout<<*(--it)<<endl;//just works fine 
    cout<<*(it-1)<<endl;//Error 
    return 0;
}

Upvotes: 0

Views: 1141

Answers (2)

blakelead
blakelead

Reputation: 1890

words.end() gives an iterator to an "element" past the end of the set. It does not point to anything so you cannot dereference it. It serves at a bound for your set. You can for example scan your set from words.end() to words.begin() :

for (set<string>::iterator it = words.begin() ; it != words.end() ; ++it)
{
    cout << *it << endl;
}

Upvotes: 1

Barry
Barry

Reputation: 302842

That's because std::set::iterator is a constant BidrectionalIterator. That means it supports ++it and --it. However, it is not a RandomAccessIterator (like std::vector::iterator) - which is what it would need to be to support it + n and it - n.

While --it and it -= 1 conceputally do the same thing, the latter requires more functionality than std::set provides. That's why it's not supported. You could always use something like: std::prev(it, 1), which would work on any iterator that satisfies the BidirectionalIterator concept.

Upvotes: 7

Related Questions