2

I want to create a vector to hold courses

 2 years ago
source link: https://www.codesd.com/item/i-want-to-create-a-vector-to-hold-courses.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

I want to create a vector to hold courses

advertisements

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);
}


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;
};

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;
};

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));
    }
  }
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK