You are here:

C++/vector script out of range - don't understand why

Advertisement


Question
the vector is a private member of my class Deck:

vector<Card> cards;

I initialize it the following way:
Deck::Deck()
{
  // create a new deck, with cards in order, but unique
  for(int i=2; i<15; i++)
  {
     for (int j=1;j<5;j++)
     {
     Card* tmp = new Card( (rank)i, (suit)j );
     cards.push_back(*tmp);
     delete tmp;
     }
rank and suit are enum types:

typedef enum {CLUB = 1, DIAMOND, HEART, SPADE} suit;

typedef enum {_EMPTY = 0, DEUCE = 2,TREY, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE} rank;
   }

it seems like the subscript out of range appears just after the first push_back() call.

it seems like i misunderstood the concept vectors, or that my initalisation is wrong, but i can't quite understand how and why.

help would be very appreciated. thanks in advance.


Answer
I like to use vector of pointers.

vector<Card *> cards;

and in the code use:

cards.push_back(tmp);

don't delete tmp in that function and to not leak memory, your ~Card destructor should then go through the vector and delete the elements.

For readability and maintainability, you can use:

for(int i=DEUCE; i<=ACE; i++)
{
for (int j=CLUB;j<=SPADE;j++)
.
.
.

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.