繁体   English   中英

类别中向量的random_shuffle的C ++执行阶段错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM