+ 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; }
6 Respostas
+ 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.
+ 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;
+ 3
no, it's iterator on element after. It is the reason why ++i under else branch.
0
try this input:{1,14 ,12 ,122 ,123}
0
it means erase return an iterator after of erasing element?
0
ok thanks