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;
}
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.
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.
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.
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With