c ++运行时错误,类中包含vector的random_shuffle

0 c++ class vector blackjack

我正在尝试编写一个二十一点游戏.我在业余时间一直在自学C++,这是我第一次在任何关于编程的网站上发帖.

我一直在寻找问题的答案,并且学到了很多东西......但这个问题让我感到非常困惑.我担心我接近完全错误的任务,希望你可以帮助我.

我有一个Card类,以及一个包含52张卡的矢量的Deck类.向量是Deck类的私有成员,我担心这是我的问题?

当我将random_shuffle行添加到我的代码中时,它编译得很好,但随后控制台窗口崩溃(Windows 7 x64,code :: blocks,c ++).我无法弄清楚我做错了什么.我调用向量随机访问迭代器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
Run Code Online (Sandbox Code Playgroud)

deck.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";
}
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助或智慧的话都会受到高度赞赏,我希望我把一切都格式化......

非常感谢

担

Ada*_*eld 6

这种访问方法:

vector <Card> get_deck() { return deck; };
Run Code Online (Sandbox Code Playgroud)

返回卡片向量的副本.因此,当您调用它两次时,您将获得两个不同的副本,并且begin()第一个副本的副本与end()第二个副本的副本不匹配,因此它会崩溃.

要修复它,您应该通过引用返回数组,以便不进行复制:

vector <Card>& get_deck() { return deck; }  // no semicolon needed here
//           ^
//           |
//    this is a reference
Run Code Online (Sandbox Code Playgroud)

但是,这允许调用者修改内部数组,这通常是个坏主意.为避免这种情况,您应该通过const引用返回它:

const vector <Card>& get_deck() { return deck; }
Run Code Online (Sandbox Code Playgroud)

但如果你这样做,那么std::random_shuffle就无法修改数组.因此,要解决这个问题,理想的解决方案是将类方法添加到Deck调用random_shuffle自身的类中.

  • 另一个选择是在Deck类本身实现shuffle. (5认同)
  • random_shuffle不适用于const_iterators. (2认同)