Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an iterator to print out every member of a set

Tags:

c++

iterator

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;
}
like image 279
user1415670 Avatar asked May 24 '12 17:05

user1415670


People also ask

How do you traverse a set?

Approach: To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element to the first element with the help of rbegin() and rend() functions. Get the set. Declare the reverse iterator on this set.

How do you find the elements of a set?

You can't access set elements by index. You have to access the elements using an iterator. set<int> myset; myset. insert(100); int setint = *myset.

How do I get the size of a set in C++?

set::size() in C++ STL size() function is used to return the size of the set container or the number of elements in the set container. Return Value: It returns the number of elements in the set container.


1 Answers

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) {
like image 146
Smi Avatar answered Nov 09 '22 20:11

Smi