[英]c++ runtime error with random_shuffle of vector in a class
我正在嘗試編寫二十一點游戲。 我在業余時間一直在自學C ++,這是我第一次在任何有關編程的網站上發帖。
我一直在尋找自己的問題的答案,並且學到了很多東西。但是這個問題使我完全困惑。 我擔心我在完成任務時完全錯了,希望您能在此方面為我提供幫助。
我有一個Card類,以及一個Deck類,可容納52張Cards。 該向量是Deck類的私有成員,我擔心這是我的問題嗎?
當我在代碼中添加random_shuffle行時,它可以正常編譯,但控制台窗口崩潰(Windows 7 x64,code :: blocks,c ++)。 我無法弄清楚我在做什么錯。 我將向量隨機訪問迭代器稱為begin()和end()...
卡座
#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
卡組
#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; };
返回紙牌向量的副本 。 因此,當您兩次調用它時,會得到兩個不同的副本,並且第一個副本的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
。
嘗試從get_deck()
返回vector<Card>&
。 在發布的代碼中,您將制作兩個單獨的副本並將其退回。
因此,當random_shuffle
嘗試執行其工作時,它random_shuffle
迭代器指向兩個不同的向量。
正如@Will在對另一個答案的注釋中指出的那樣,最好通過實現方法void Deck::shuffle()
來保留封裝,該方法在成員deck
上調用random_shuffle
而不完全公開deck
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.