从C ++向量中移除和混洗

时间:2013-10-27 01:40:16

标签: visual-c++ vector stl shuffle erase

我使用向量来表示c ++中的一副牌。我无法洗牌并移除第一个元素。

改组不起作用,矢量保持相同的顺序。我在我的程序中,在Deck的构造函数中调用了一次重新种子。 int random每次都不同。我试过时间(NULL)和时间(0)。改组:

void Deck::reseed() {
srand(time(NULL));
}

void Deck::shuffle() {
int random = rand();
for(int i = 0; i < random; i++) {
    std::random_shuffle(deckVec.begin(), deckVec.end());
}
}

删除不起作用,删除最后一个元素而不是第一个元素(例如,元素16被删除而不是元素0)。删除:

Card Deck::dealCard() {
//other code...
Card& tempCard = deckVec.front();
std::vector<Card>::iterator temp = deckVec.begin(); //This if for debugging, and 
                                                    //this pointer is correct   
deckVec.erase(deckVec.begin()); 
return tempCard; //the correct card is returned
    }

任何帮助都将不胜感激。

-----------更新---------------- shuffle之前和之后的打印代码:

cout << deck.toString(); //output: Suit: Clubs, Rank: 2
                         //        Suit: Clubs, Rank: 3 ...   
//shuffle if there are three arguments
if(argc == 3)
   deck.shuffle();
cout << deck.toString();//output: Suit: Clubs, Rank: 2
                        //        Suit: Clubs, Rank: 3 ... (identical to above) 

很难展示dealCard。基本上,我在这里称之为:

void operator<<(Hand& hand, Deck& deck) {
    hand.addCard(deck.dealCard());
}

然后我打印出内容。输出为:C2 C2 C2 C2 ...为2个俱乐部。它们都是套牌中的第一张牌。

for(int i = 0; i < 5; i++) {
            for(unsigned int j = 0; j < hands.size(); j++) {
                try {
                hands.at(j) << deck;
                } catch(int& i) {
                    cout << "no cards left" << endl;
                }
            }
        }

        //print out the contents
        cout << deck.toString() << endl;
        for(unsigned int i = 0; i < hands.size(); i++) {
            cout << "Hand " << i << ": ";
            cout << hands.at(i).toString() << endl;
        }

0 个答案:

没有答案