TheDudeAbides
TheDudeAbides

Reputation: 430

How to copy elements of a vector to a stack in c++

I want to make a stack of cards using a special Card class I created myself.

Now what I want to do is: I want the cards in a stack for easier later use, but the cards have to be shuffled and that's not possible on a stack.

Here's the code

Card dummyCard;
vector<Card> dummyVector;
initializeCards( dummyVector, dummyCard, 5 ); /* this function puts cards in vector */
random_shuffle( dummyVector.begin(), dummyVector.end() );
copy( dummyVector.begin(), dummyVector.end(), cardPile ); /* cardPile is a stack */

Any idea on how to make this work? Or should I just keep the vector as my substitute for stack? and use pop_back and push_back?

Upvotes: 0

Views: 200

Answers (2)

shreyasva
shreyasva

Reputation: 13546

You can iterate through the vector and push elements one-by-one

for (vector<Card>::iterator i = dummyVector.begin(); i != dummyVector.end(); i++) {
  cardPile.push(*i);
}

Upvotes: 1

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36451

What about this?

#include <stack>
#include <vector>
using namespace std;

int main()
{
    vector<int> x;
    x.push_back(10); x.push_back(20); x.push_back(30);

    stack< int,vector<int> > stack(x);

    return 0;
}

Upvotes: 1

Related Questions