我对C++相当陌生,并开始编写一个小型扑克游戏,以帮助我获得更多有关向量的经验。我在第二个函数中遇到了运行时错误,在阅读下面的文章后发现我误解了reserve()类成员的行为,这真的不是什么新鲜事。我相信我可以用resize()来补救这个问题,但是我希望能够通过一种方式来创建一些输入,以便我可以重新构建这个动态分配的函数。我在动态分配方面遇到的困难是,我试图让交易功能像真正的纸牌游戏一样向每个玩家分发纸牌(是的,我意识到这在统计上是多余的)。我可以很容易地用c中的指针数学来做到这一点,我想我可以通过静态分配这些向量来解决这个问题,但我更愿意尽可能地使用C++作为优雅和高效的。任何建议的动态做到这一点?也就是说,我怎样才能完全避免为deal()
函数中使用的容器分配或预留空间?代码超出范围。这个向量如何动态分配?
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;
}
输出:
[email protected]:~/src/poker$ ./poker
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 1) >= this->size() (which is 0)
Aborted
回溯:
#0 0x00007ffff74aa428 in __GI_raise ([email protected]=6)
at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff74ac02a in __GI_abort() at abort.c:89
#2 0x00007ffff7ae484d in __gnu_cxx::__verbose_terminate_handler()()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff7ae26b6 in ??() from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff7ae2701 in std::terminate()()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff7ae2919 in __cxa_throw()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x00007ffff7b0b3f7 in std::__throw_out_of_range_fmt(char const*, ...)()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7 0x000000000040218c in std::vector<int, std::allocator<int> >::_M_range_check(unsigned long) const()
#8 0x0000000000401785 in std::vector<int, std::allocator<int> >::at(unsigned long)()
#9 0x0000000000401030 in main()
你得到什么错误? –
查看上面,添加更多的输出信息 – mreff555
查看'deal'后的'hand'的大小' –