Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 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?
13 Answers
+ 10
If you want a simple fix, add
it--;
after
l.insert(it, aux*2);
+ 13
I got stuck on the saving loop of death but on line 22 you are incrementing the iterator
++it;
and then inserting,
and then the for loop is incrementing it.
i commented it out and it worked fine ;)
+ 13
lol reason being is that lists push the inserted number to the back, and pop from the front.
so, for example, inserting 1 2 3 4 will output 4 3 2 1.
Its like cramming stuff into a box. The first thing you put in will be at the very bottom and the first thing you take out should be from the top.
to output in order you'll have to input backwards ;)
Glad you found a built in way though and youre welcome ^^
+ 11
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 🍪
+ 11
Ok, thanks. I'll try iterating backwards and I'll post the result.
+ 11
youre welcome and alright ;)
+ 11
Hatsy Rei thanks, works like a charm!
+ 11
I appreciate your help, feel free to do it when you have time.
+ 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: 🍪
+ 5
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.
+ 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,
+ 1
Anime FanGirl Have you tried as I mentioned above?
it is working I have confirmed.
0
that's right!