Using an iterator to print each member of a set

I am trying to use an iterator to print each member of a set. As far as I can tell from the 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 once. If I uncomment the line using * iter, Visual Studio throws an exception from the runtime saying that "map / set iterator is not decompressible." 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;
}
+3
source share
1 answer

You have an extra ;in this line:

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

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

So, change this line to this:

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

All Articles