+ 2

what is wrong with this code?printing the odd number

//it is giving 8 as output which is even #include <iostream> #include <set> using namespace std; int main() { // set declaration set<int> myset{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // checking for even elements and removing them for (auto i = myset.begin(); i != myset.end(); ++i) { if (*i % 2 == 0) { myset.erase(i); i--; } } // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0; }

21st Sep 2018, 4:14 AM
Bahubali
Bahubali - avatar
6 Answers
+ 5
The problem on my side appears to be the i--; statement after myset.erase(i). Removing i-- gives me a correct output of 1 3 5 7 9 while the original code gives me no output at all.
21st Sep 2018, 4:28 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
i-- while i was invalidated by erase. do i=myset.erase(); The second error due to 1%2!=0; So, you erase the first item and then do i--. The right way is to not move iterator in the for statement. for(auto i=m.begin(); i!=m.end();) if(*i%2==0) i=m.erase(i); else ++i;
21st Sep 2018, 4:34 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 3
no, it's iterator on element after. It is the reason why ++i under else branch.
21st Sep 2018, 4:48 AM
Sergey Ushakov
Sergey Ushakov - avatar
0
try this input:{1,14 ,12 ,122 ,123}
21st Sep 2018, 4:33 AM
Bahubali
Bahubali - avatar
0
it means erase return an iterator after of erasing element?
21st Sep 2018, 4:43 AM
Bahubali
Bahubali - avatar
0
ok thanks
21st Sep 2018, 5:28 AM
Bahubali
Bahubali - avatar