タイトルが示すように、乱数を要素として整数型のベクトルに追加することに問題がありました。ベクトル ライブラリと連携して動作するように、time ライブラリと stdlib ライブラリを含めました。
これまでの私の試み(クラスを使用)は次のとおりです。
ベクトルにランダムな要素を追加する関数に、参照によってベクトルを渡すこと。さらに、更新したい変数への参照を渡し、クラスで宣言され、コンストラクターで定義されたポインターを使用して、変数のメモリアドレスを保持します (前の行で参照されたものと同じ)。
class PlayerHand
{
public:
playerHand();
void populateHand(vector<int>&, int&)
private:
vector<int> &refVector;
int *pPointer;
int giveCard;
};
playerHand::playerHand()
{
srand((time(NULL)));
giveCard = (rand() % 14) + 1;
pPointer = &giveCard;
}
void playerHand::populateHand(vector<int> &refVector, int &refGiveCard)
{ for( int i = 0; i <= 8; i++)
{
refVector.push_back(*pPointer); //dereference thepointer to store value in giveCard
srand(time(0));
refGiveCard = (rand() %14) + 1; /*Here is where I'm trying to update the reference
so before the next loop, the reference should have
a new updated value*/
cout << refVector.at(i) << " ";
}
}
したがって、コードをコンパイルした後、ベクトル内の要素はすべて同じ数であり、違いはありません。コードでどのような間違いを犯していますか?