Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting and pushing back elements of a vector in C++

Tags:

c++

vector

I am trying to solve a problem that is similar to this one : Throwing cards away. The only change in my problem is that I don't need the sequence of discarded cards. I only want the last remaining card.

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main(void)
{
    int n, i;
    while ((scanf ("%d", &n) == 1) && n != 0)
    {
        vector<int> cards;
        for (i = 1; i <= n; ++i)
        {
            cards.push_back(i);
        }
        while (cards.size() != 1)
        {
            cards.erase(cards.begin());
            cards.push_back(cards.front());
        }
        printf ("%d\n", cards.at(1));
    }
    return 0;
}

This is the first time I am using vector and all the related STL functions. I checked this and it says that the erase function deletes a vector element. So the while loop should should keep decreasing the size of the vector till it becomes 1. But I am not getting an output on running this. I think it's because of an infinite loop, so I tried printing the size of the vector in each iteration and saw that the size is reduced only once. So this is causing the infinite loop. However I don't understand why it's not being reduced further.

like image 731
reb94 Avatar asked Jan 24 '26 18:01

reb94


2 Answers

The size of your vector never drops to 1 because you do not move the front card, but copy it to the end of vector. cards.push_back(cards.front()) increases the size by one. If your aim is to move the front card to the back of vector then exchange the two lines:

    while (cards.size() != 1)
    {
        cards.push_back(cards.front());
        cards.erase(cards.begin());
    }

This would not decrease the size of course.

EDIT: Here's the proposed solution which removes the front card and moves the next card to the bottom of the deck (vector).

    while (cards.size() != 1)
    {
        cards.erase(cards.begin());
        cards.push_back(cards.front());
        cards.erase(cards.begin());
    }

The size will effectively decrease by 1 in each iteration.

like image 50
Igor Popov Avatar answered Jan 27 '26 06:01

Igor Popov


    while (cards.size() != 1)
    {
        cards.erase(cards.begin()); // cards.size() goes down
        cards.push_back(cards.front()); // cards.size() goes up
    }
like image 41
just somebody Avatar answered Jan 27 '26 06:01

just somebody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!