user1415670
user1415670

Reputation: 91

Using an iterator to print out every member of a set

I'm trying to use an iterator to print out every member of a set. As far as I can tell from other stackoverflow answers, I have the correct formatting. When I run this code, it correctly outputs that the size of myset is 3, but it only outputs ii once. If I uncomment the line with *iter, Visual Studio throws a runtime exception saying that that "map/set iterator is not dereferencable. Any idea why?

int main()
{
set<int> myset;
myset.insert(5);
myset.insert(6);
myset.insert(7);
set<int>::iterator iter;
cout<<myset.size()<<endl;
int ii=0;
for(iter=myset.begin(); iter!=myset.end();++iter);{
    //cout<<(*iter)<<endl;
    ii+=1;
    cout<<ii<<endl;
}
return 0;
}

Upvotes: 6

Views: 38171

Answers (1)

Smi
Smi

Reputation: 14316

You have an extra ; in this line:

for(iter=myset.begin(); iter!=myset.end();++iter);{

This means that the loop's body is actually empty, and the following lines are executed once only.

So change that line to this:

for(iter=myset.begin(); iter!=myset.end();++iter) {

Upvotes: 13

Related Questions