I have a function in deck.cpp which deals random cards from a deck:
QVector<card> Deck::deal_rand_cards(QVector<card> vDeck, int quantity)
{
QVector<card> vDealt;
int deckSize = vDeck.size();
card randCard;
qsrand(QTime::currentTime().msec());
for (int i=0;i<quantity;i++)
{
int rn=rand()%deckSize;
randCard = vDeck[rn];
qDebug()<<vDeck.size();
vDealt.append(randCard);
vDeck.remove(rn);
}
return vDealt;
}
My issue is that everytime the function is run from mainwindow.cpp, vDeck contains the full deck, instead of the deck minus dealt cards which i removed with the function.
If I deal 3 cards twice, debug prints:
54 53 52 54 53 52
How to update a variable within a function that is used by other functions and in other files? I have a feeling a pointer is involved, but I still don’t quite grasp the concept.
Thanks
here’s deck.h
#ifndef DECK_H
#define DECK_H
#include <QString>
#include <QVector>
struct card
{
QString suit;
QString color;
int rank;
};
class Deck
{
private:
int size;
int jokers;
public:
QVector<card> build_deck(int deckSize, int jokers);
QVector<card> deal_rand_cards(QVector<card> vDeck, int quantity);
};
#endif // DECK_H
You need to pass reference of vDeck into
deal_rand_carsfunction, currently you are working on a copy of vDeck.If you use a reference as an argument, the function works with the original data instead of with a copy.