简体   繁体   中英

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?

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;
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM