I'm fairly new to c++ and started writing a small poker game to help me get some more experience with vectors. I'm getting a runtime error in the second function, which is really no surprise after reading the post below and discovering I was misunderstanding the behavior of the reserve() class member. I believe I could probably remedy this with resize() but I was hoping for some creative input on a way that I could re-construct this function to allocate dynamically. The difficulty I'm having with the dynamic allocation is that I am trying to make the deal function distribute cards to each player as in a real card game (yes I realize that this is somewhat statistically superfluous). I could do this with pointer math in c fairly easily, and I think I could fix this by statically allocating some of these vectors, but I would prefer to utilize c++ as elegant and efficient as possible. Any suggestions on a way to do this dynamically?
Choice between vector::resize() and vector::reserve()
#include <cassert>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
const int __handSize__ = 5;
class Hand {
public:
std::vector<int> held;
std::vector<int> played;
};
std::vector<int> shuffle() {
std::vector<int> deck;
for( int i = 0; i < 52; i++ ){
deck.push_back( i );
}
std::random_shuffle(deck.begin(), deck.end());
assert( 52 == deck.size() );
return deck;
}
std::vector<Hand> deal( int nPlayers, std::vector<int> &deck ) {
std::vector<Hand> playerHands;
playerHands.reserve( nPlayers );
for( int i = 0; i > __handSize__; i++ ) {
for( int j = 0; j < nPlayers; j++ ) {
playerHands.at(j).held.push_back( deck.back() );
}
}
return playerHands;
}
int main() {
srand(time( NULL ));
std::vector<int> deck = shuffle();
std::vector<Hand> hand = deal( 3, deck );
std::cout << hand.at(1).held.at(1) <<std::endl;
}
Aucun commentaire:
Enregistrer un commentaire