我正在尝试编写二十一点游戏的代码。我一直在业余时间自学C++,这是我第一次在任何网站上发布有关编程的文章。
我一直在寻找我的问题的答案,并且学到了很多东西..但是这个问题完全让我感到困惑。我担心我完全错误地完成了任务,希望你能帮助我解决这个问题。
我有一个 Card 类和一个包含 52 张卡片 vector 的 Deck 类。 vector 是 Deck 类的私有(private)成员,我担心这是我的问题?
当我将 random_shuffle 行添加到我的代码时,它可以正常编译,但随后控制台窗口崩溃(Windows 7 x64,code::blocks,c++)。我不知道我做错了什么。我将 vector 随机访问迭代器称为 begin() 和 end()...
deck.h
#ifndef DECK_H
#define DECK_H
#include <vector>
using namespace std;
/** Card Class */
class Card
{
public:
/** Constructor prototypes */
//Card(); //default constructor
Card(int s, int r) : suit(s), rank(r) {}
/** GET function prototypes */
int getRank(); // returns card number as int
string getSuit(); // returns the suit in a string
private:
int rank;
int suit;
} ;
/** Deck class */
class Deck
{
public:
Deck();
vector <Card> get_deck() { return deck; };
private:
vector<Card> deck;
};
#endif // DECK_H
甲板.cpp
#include <iostream>
#include <string>
#include <vector>
#include "deck.h"
using namespace std;
/** Deck ctor to initialise deck */
Deck::Deck()
{
for(int suit = 0; suit < 4; suit++)
{
for(int rank = 0; rank < 13; rank++)
{
deck.push_back(Card(suit,rank));
}
}
}
/** Functions to GET rank and suit */
// Function to get rank as int
int Card::getRank()
{
return rank;
}
// Function to get suit as string
string Card::getSuit()
{
switch(suit)
{
case 0:
return "Diamonds";
case 1:
return "Hearts";
case 2:
return "Clubs";
case 3:
return "Spades";
default:
return "Error";
}
}
main.cpp
#include <iostream>
#include <algorithm>
#include <ctime> // time()
#include <string>
#include <vector>
#include "deck.h"
using namespace std;
int main()
{
Deck mydeck;
random_shuffle( mydeck.get_deck().begin(), mydeck.get_deck().end() );
// Loop to iterate through deck of cards
for(int i = 0; i<52; i++)
{
cout << mydeck.get_deck()[i].getRank() << " of " << mydeck.get_deck()[i].getSuit() << endl;
}
// Display size of deck
//cout << endl << "The size of deck is: " << mydeck.get_deck().size() << endl;
return 0;
}
任何帮助或智慧之言将不胜感激,我希望我的格式正确...
非常感谢
丹
最佳答案
此访问器方法:
vector <Card> get_deck() { return deck; };
返回卡片 vector 的拷贝。所以当你调用它两次时,你会得到两个不同的拷贝,第一个拷贝的 begin()
与第二个拷贝的 end()
不匹配, 所以它崩溃了。
要修复它,您应该通过引用返回数组,这样就不会创建拷贝:
vector <Card>& get_deck() { return deck; } // no semicolon needed here
// ^
// |
// this is a reference
但是,这允许调用者修改内部数组,这通常不是一个好主意。为避免这种情况,您应该通过 const
引用返回它:
const vector <Card>& get_deck() { return deck; }
但如果您这样做,则 std::random_shuffle
无法修改数组。因此,要解决此问题,理想的解决方案是向 Deck
类添加一个类方法,该类会自行调用 random_shuffle
。
关于c++运行时错误,类中 vector 的random_shuffle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13161699/