+ 14

[Solved]List inserting

I have a list of n integers. I'm trying to add after each even number it's double. Below is my try: #include <iostream> #include <list> using namespace std; int main() { int n, x, aux; cin >> n; list<int> l; for(int i = 0; i < n; i++){ cin >> x; l.push_back(x); } list<int>::iterator it; it = l.begin(); for( ; it != l.end(); ++it){ aux = *it; if( aux % 2 == 0){ ++it; l.insert(it, aux * 2); } continue; } list<int>::iterator j; for(j = l.begin(); j != l.end(); ++j) cout << *j << " "; return 0; } It works, but the doubles are added twice. I've tried to increase the iterator and the continue keyword but I've got the same results. How can I fix this?

15th Jun 2018, 2:00 PM
A Fox
A Fox - avatar
10 Antworten
+ 9
If you want a simple fix, add it--; after l.insert(it, aux*2);
15th Jun 2018, 5:35 PM
Hatsy Rei
Hatsy Rei - avatar
+ 10
I removed it and it inserts the doubled number before, but the problem I'm solving requires it to be after. Using list::unique seems to fix it. I'm still open to another way of solving this problem. Thanks for the response 🍪
15th Jun 2018, 5:00 PM
A Fox
A Fox - avatar
+ 10
Ok, thanks. I'll try iterating backwards and I'll post the result.
15th Jun 2018, 5:16 PM
A Fox
A Fox - avatar
+ 10
Hatsy Rei thanks, works like a charm!
15th Jun 2018, 5:40 PM
A Fox
A Fox - avatar
+ 10
I appreciate your help, feel free to do it when you have time.
15th Jun 2018, 5:46 PM
A Fox
A Fox - avatar
+ 10
SagaTheGreat it inserts the doubled number at the beginning of the list, but I needed it to be after the number. Here's a cookie for your attempt: 🍪
18th Jun 2018, 12:27 PM
A Fox
A Fox - avatar
+ 4
Iterating through a list while adding elements to it can be tricky since it involves iterators re-adjusting themselves, and it's late here so I can't really handtrace it out for now.
15th Jun 2018, 5:43 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
I think ++it is the cause. If you remove that line then it should work fine. Like below, if( aux % 2 == 0) { l.insert(it, aux * 2); } Another solution is you can do like below; if( aux % 2 == 0) { l.push_front(aux * 2); } Thanks,
16th Jun 2018, 11:52 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
Anime FanGirl Have you tried as I mentioned above? it is working I have confirmed.
16th Jun 2018, 4:29 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
that's right!
17th Jun 2018, 6:30 AM
Василий Сяськин