我想创建一个向量来容纳课程 [英] I want to create a Vector to hold classes
问题描述
我对制作一个向量来容纳类非常困惑。
如果我想在单个向量中保存一堆数据,例如下面的示例。然后将数据写入类成员函数中,并可以被其他函数调用和使用。
Im very confused about making a vector to hold classes. if i wanted to hold a bunch of data in a single vector like the example below. then have the data written in a class member function, and able to be called out and used by other functions.
我在哪里粘贴矢量声明?
请帮忙!
where do i stick the vector declaration? please help!
#include <vector>
class Card
{
public:
int suit;
int rank;
Card::Card(int suit, int rank);
Function();
};
vector<Card> cards;
int main()
{
}
Card::Function()
{
for loop...
Card cardz(i, i);
cards.push_back(cardz);
}
推荐答案
在我看来,您正在扩展 Card
对象应该执行的操作的范围。我可以建议以下布局吗?首先定义一张单张卡。
It seems to me that you're stretching the bounds of what a Card
object should do. May I suggest the following layout? First defines a single card.
class Card {
public:
Card(int s, int r)
: suit(s), rank(r) {
// Initialize anything else here
}
private:
int suit, rank;
};
接下来,定义一个保存 vector
卡并对其进行操作。我们称之为 Deck
Next, define an object which holds a vector
of cards and manipulates them. Let's call it Deck
class Deck {
public:
Deck();
private:
vector <Card> cards;
};
现在,在您的 Deck
类中,您可以根据需要初始化纸牌集合。
Now, in your Deck
class, you can initialize the collection of cards as you see fit.
Deck::Deck() {
for (int suit = 0; suit < 4; suit++) {
for (int rank = 0; rank < 13; rank++) {
cards.push_back(Card(suit, rank));
}
}
}
这篇关于我想创建一个向量来容纳课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!