Insert a card into a deck of cards - c++

So i have this program and i want to implement an insert void function. Basically i want to insert a card into the deck. The output should be a deck of cards and the shuffled version and then insert a card and sort it again. How can i accomplish that?
Deck.cpp
#include "deck.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <random>
#include <chrono>
using namespace std;
/**
* Help function to convert Suit enum to string
*/
const string SuitToString(Suit s) {
switch (s) {
case Suit::Hearts:
return "H";
case Suit::Diamonds:
return "D";
case Suit::Spades:
return "S";
case Suit::Clubs:
return "C";
}
return "";
}
Card::Card(int rank, Suit suit)
{
this->rank = rank;
this->suit = suit;
}
/**
* Overload of << operator for Card class
*/
ostream & operator << (ostream &out, const Card &c)
{
string r;
switch(c.rank) {
case 1:
r = 'A';
break;
case 11:
r = 'J';
break;
case 12:
r = 'Q';
break;
case 13:
r = 'K';
break;
default:
r = to_string(c.rank);
break;
}
out << r << SuitToString(c.suit);
return out;
}
/**
* Create a deck of 52 cards
*/
Deck::Deck() {
for (Suit s = Suit::Hearts; s <= Suit::Clubs; s = Suit(s + 1)) {
for (int r=1; r<14; r++) {
cards.push_back(Card(r, s));
}
}
}
/**
* Overload of << operator for Deck class
*/
ostream & operator << (ostream &out, const Deck &d)
{
string separator;
for (auto i: d.cards) {
out << separator << i;
separator = ", ";
}
return out;
}
/**
* Return number of cards in deck
*
*/
int Deck::size()
{
return this->cards.size();
}
/**
* Shuffle all the cards in deck in ranom order.
*/
void Deck::shuffle()
{
auto rng = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());
std::shuffle(this->cards.begin(),this->cards.end(), rng);
}
/**
* Sort the deck according to card rank. All aces, the all two's, then all threes, ...
*/
void Deck::sort()
{
vector<Card> sorted_cards; // Empty temporary deck
while (this->size() > 0) {
// Go through the deck from left to right, insert the deck in the appropriate spot
Deck::insert(sorted_cards, this->take()); //Take a card from the old deck, insert it into the new one
}
this->cards = sorted_cards;
}
/**
* Take the top card from the deck
*/
Card Deck::take() {
Card c = this->cards.back();
this->cards.pop_back();
return c;
}
/**
* Put a card on top of the deck
*/
void Deck::put(Card card) {
cards.push_back(card);
}
void Deck::insert(vector<Card> &cardlist, Card card) {
/**
* My insert code here!
*/
return;
}
Deck.h
#include <iostream>
#include <vector>
#include <string>
using namespace std;
enum Suit {
Hearts,
Diamonds,
Spades,
Clubs
};
class Card
{
private:
int rank;
Suit suit;
public:
Card(int rank, Suit suit);
bool operator == (Card const &other)
{
return rank == other.rank;
}
bool operator < (Card const &other)
{
return rank < other.rank;
}
bool operator > (Card const &other)
{
return rank > other.rank;
}
friend ostream & operator << (ostream &out, const Card &c);
};
class Deck
{
private:
vector<Card> cards;
public:
Deck();
friend ostream & operator << (ostream &out, const Deck &d);
int size();
void shuffle();
void sort();
Card take();
void put(Card card);
static void insert(vector<Card> &cardlist, Card card);
};
main.cpp
#include "deck.h"
#include <iostream>
using namespace std;
main() {
Deck deck = Deck();
cout << "Fresh deck: " << deck << endl;
deck.shuffle();
cout << "Shuffled deck: " << deck << endl;
deck.sort();
cout << "Sorted deck: " << deck << endl;
}
For now i just have written the function itself.

Since Deck::insert is being called from the Deck::sort method, I think the aim is to insert the new card in order with respect to the previously inserted (and therefore already sorted) cards.
So it seems you need something like this
void Deck::insert(vector<Card> &cardlist, Card card) {
// starting from zero
size_t i = 0;
// find the index of the first card in the list that is >= to the card to insert
for (; i < cardList.size(); ++i)
{
if (card < cardList[i])
break;
}
// insert the new card before that index
cardList.insert(cardList.begin() + i, card);
}
This is bad code, for a couple of reasons (efficiency and design) but the above is my take on what you are being asked to do.

Related

Output a Vector Element of Enum Class Type in C++

I have created card and deck classes for use in a C++ poker game, however, I'm trying to check that my assignment of vector elements are correct and having issues displaying them on the console. I have an enumerated class for the suits and integer values for the ranks. I see that my deck vector is generating with 52 cards, but I'm not sure how to correctly get this to display on the screen using the card class display() function for each vector element. Any help would be appreciated.
Note: I'm also guessing an alternate method would be to overload the output stream operator to display a vector element that is an object with an enumerated class parameter, but also not sure on what that syntax would look like.
int main(){ Deck deck();}
Card.h
#pragma once
#include <stdlib.h>
#include <iostream>
using namespace std;
enum class Suit { Hearts, Diamonds, Spades, Clubs };
class Card
{
private:
Suit m_suit;
int m_rank;
public:
Card();
Card(int r, Suit s);
void display();
int getRank();
void setRank(int);
Suit getSuit();
void setSuit(Suit);
};
Card.cpp
#include "Card.h"
#include <iostream>
#include <string>
Card::Card(): m_rank(0), m_suit(Suit::Hearts)
{
}
Card::Card(int r, Suit s)
{
m_rank = r;
m_suit = s;
}
void Card::display()
{
if (m_rank == 1) // for number cards, show value
{
std::cout << "Ace";
}
else if ((2 <= m_rank) && (m_rank <= 10))
{
std::cout << m_rank;
}
else
{
switch (m_rank)
{
case 11:
std::cout << "Jack";
break;
case 12:
std::cout << "Queen";
break;
case 13:
std::cout << "King";
break;
default:
std::cout << "INVALID RANK";
}
}
switch (m_suit) // display suit
{
case Suit::Hearts:
std::cout << " of Hearts";
break;
case Suit::Diamonds:
std::cout << " of Diamonds";
break;
case Suit::Spades:
std::cout << " of Spades";
break;
case Suit::Clubs:
std::cout << " of Clubs";
break;
};
}
int Card::getRank()
// return the numeric value of a card
{
return (m_rank);
}
Deck.h
#pragma once
#include <vector>
#include "Card.h"
class Deck
{
private:
Card card;
std::vector<Card> m_deck;
public:
Deck();
void shuffle();
void grabCard();
};
Deck.cpp
#include "Deck.h"
#include "Card.h"
#include <vector>
Deck::Deck()
{
for (int i = 1; i < 14; i++)
{
for (int j = int(Suit::Hearts); j <= int(Suit::Clubs); j++)
{
m_deck.push_back(Card(int(i), Suit(j))); //passing the card constructor to create a card object, then store it as a vector element
int counter = 0; // use to print out each element
std::cout << m_deck[card.display()]; //output each card obect via display method
std::cout << "\t\n";
counter++;
}
}
}
void Deck::shuffle()
{
}
void Deck::grabCard()
{
}
To display vector element, you should call display() of the vector element to display.
std::cout << m_deck[card.display()];
should be
m_deck.back().display();
to have it display the last pushed card.
Also int main(){ Deck deck();} is a main function with only function declaration and Deck::Deck() won't be called.
To call the constructor, it should be int main(){ Deck deck;}.

Vector member always zero size on call to member function that uses push_back to add to the vector member

What I am trying to do is add cards to a vector that is to be a Blackjack hand, but each time I enter the function that uses push_back to add a card to the vector, the vector starts out empty. The problem is in my Hand class in the addCardToHand function, and the same issue is present in the same class in my showHand function. I have whittled the code down as much as I could but still present a full working version with the issue. I cannot figure out why my Hand class treats the hand as brand new every time I call a function in the class. Please advise.
// Card.h
#ifndef CARD_H
#define CARD_H
#include <string>
#include <array>
class Card {
private:
int rank;
int suit;
int hardValue;
int softValue;
static const std::array<std::string,14> ranks;
static const std::array<std::string,5> suits;
public:
Card();
Card(int rank, int suit);
int getHardValue() const;
int getSoftValue() const;
std::string toString() const;
};
#endif
// Card.cpp
#include "Card.h"
const std::array<std::string,14> Card::ranks {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
const std::array<std::string,5> Card::suits {"","C","D","H","S"};
Card::Card() : rank(0), suit(0) {
hardValue = 0;
softValue = 0;
}
Card::Card(int rank, int suit) : rank(rank), suit(suit) {
if (rank == 1) {
hardValue = 1;
softValue = 11;
}
else if (rank <= 10) {
hardValue = rank;
softValue = rank;
}
else {
hardValue = 10;
softValue = 10;
}
}
int Card::getHardValue() const {
return hardValue;
}
int Card::getSoftValue() const {
return softValue;
}
std::string Card::toString() const {
return ranks[rank] + suits[suit];
}
// Shoe.h
#ifndef SHOE_H
#define SHOE_H
#include <vector>
#include <random>
#include "Card.h"
class Shoe {
private:
int numDecksInShoe;
std::vector<Card> shoe;
static int currentCard;
static int maxDealCard;
static const unsigned long int seed;
static std::mt19937 randEng;
void renewShoe();
public:
Shoe();
explicit Shoe(int numDecksInShoe);
std::vector<Card> getShoe() const;
int getCurrentCard() const;
int getMaxDealCard() const;
void shuffle();
Card dealCard();
};
#endif
// Shoe.cpp
#include <ctime>
#include "Shoe.h"
const unsigned long int Shoe::seed = static_cast<unsigned long int>(std::time(nullptr));
std::mt19937 Shoe::randEng(seed);
int Shoe::currentCard = 0;
int Shoe::maxDealCard = 51;
Shoe::Shoe() {
}
Shoe::Shoe(int decksInShoe) {
numDecksInShoe = decksInShoe;
int count = 0;
for (int i = 0; i < numDecksInShoe; i++) {
for (int suit = 4; suit >= 1; suit--) {
for (int rank = 1; rank <= 13; rank++) {
Card card(rank,suit);
shoe.push_back(card);
count += 1;
}
}
}
currentCard = 0;
maxDealCard = count - 1;
}
std::vector<Card> Shoe::getShoe() const {
return shoe;
}
int Shoe::getCurrentCard() const {
return currentCard;
}
int Shoe::getMaxDealCard() const {
return maxDealCard;
}
void Shoe::shuffle() {
Card temp;
std::uniform_int_distribution<int> deckDist(0,numDecksInShoe*52-1);
int index;
for (int i = 0; i < numDecksInShoe*52; i++) {
do {
index = deckDist(randEng);
} while (index == i);
temp = shoe[index];
shoe[index] = shoe[i];
shoe[i] = temp;
}
std::uniform_int_distribution<int> maxDeal(10,41);
int tempMax = (numDecksInShoe-1)*52 - 1;
maxDealCard = tempMax + 51 - maxDeal(randEng);
}
Card Shoe::dealCard() {
if (currentCard == maxDealCard) {
renewShoe();
}
Card dealCard = shoe[currentCard];
currentCard += 1;
return dealCard;
}
void Shoe::renewShoe() {
Shoe newShoe(numDecksInShoe);
shoe = newShoe.getShoe();
shuffle();
}
here is my Hand class
// Hand.h
#ifndef HAND_H
#define HAND_H
#include <vector>
#include <string>
#include "Card.h"
class Hand {
private:
std::vector<Card> hand;
public:
Hand();
std::vector<Card> getHand() const;
void addCardToHand(Card card);
void clearHand();
Card revealBottomCard();
std::string showHand() const;
std::string peakHand() const;
};
#endif
// Hand.cpp
#include <iostream>
#include "Hand.h"
Hand::Hand() {
}
std::vector<Card> Hand::getHand() const {
return hand;
}
void Hand::addCardToHand(Card card) {
std::cout << card.toString() << std::endl;
hand.push_back(card);
}
void Hand::clearHand() {
hand.clear();
}
std::string Hand::showHand() const {
std::string returnString = "";
for (int i = hand.size()-1; i >= 1; i--) {
returnString += hand[i].toString() + "\n";
}
returnString += "XX\n";
return returnString;
}
std::string Hand::peakHand() const {
std::string returnString = "";
for (int i = hand.size()-1; i >= 0; i--) {
returnString += hand[i].toString() + "\n";
}
return returnString;
}
here is the Table class that has the code that calls the Hand class functions
// Table.h
#ifndef TABLE_H
#define TABLE_H
#include "Shoe.h"
#include "Player.h"
class Table {
private:
Shoe shoe;
public:
explicit Table(Shoe shoe);
Shoe getShoe() const;
void clearHand(std::vector<Player> players);
void dealHand(std::vector<Player> players);
};
#endif
// Table.cpp
#include <iostream>
#include "Table.h"
Table::Table(Shoe shoe) : shoe(shoe) {
}
Shoe Table::getShoe() const {
return shoe;
}
void Table::clearHand(std::vector<Player> players) {
for (Player &player : players) {
player.getHand().clearHand();
}
}
void Table::dealHand(std::vector<Player> players) {
for (int i = 0; i <= 1; i++) {
for (Player &player : players) {
player.getHand().addCardToHand(shoe.dealCard());
}
}
}
// Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include "Hand.h"
class Player {
private:
std::string name;
Hand hand;
double money;
public:
explicit Player(std::string name, double money = 1000.0);
std::string getName() const;
Hand getHand() const;
double getMoney() const;
};
#endif
// Player.cpp
#include "Player.h"
Player::Player(std::string name, double money) : name(name), money(money) {
}
std::string Player::getName() const {
return name;
}
Hand Player::getHand() const {
return hand;
}
double Player::getMoney() const {
return money;
}
and finally here is a short driver that runs and displays the issue
// blackjack testing
#include <iostream>
#include "Player.h"
#include "Table.h"
int main() {
std::vector<Player> players {Player("Tom",1500.0),Player("Sue"),Player("Dave")};
Shoe shoe1(6);
Table table1(shoe1);
table1.dealHand(players);
for (Player player : players) {
std::cout << player.getName() << "'s hand\n";
std::cout << player.getHand().showHand() << "\n\n";
}
}
The output is below. I printed out the cards that were added to the hand vector (and then 'forgotten') and below that above the XX's, if everything were to work correctly you should see the 4, 5 and 6 of spades since I did not shuffle the deck. The XX's are to simulate face down bottom card.
AS
2S
3S
4S
5S
6S
Tom's hand
XX
Sue's hand
XX
Dave's hand
XX
Sorry for dumping all this code in here, but I wanted to provide a full working solution and this is as small as I could get it. Thanks for any help.
player.getHand().addCardToHand(...);
player.getHand() returns a temporary Hand object that's a copy of player.hand. Then you add a card to that temporary object. Then that temporary object dies, added card and all. player.hand remains unchanged. This line of code is an elaborate no-op.
To add on #Igor's answer, the best way to fix this should probably return a reference instead:
const Hand& Player::getHand() const {
return hand;
}
I made this a const because returning a non-const could (potentially) allow you to break constness of a constant Player object. That is just inviting potential bugs.
Because of this, you may want to add a non-const version too:
Hand& Player::getHand() {
return hand;
}
Now you can't modify a const Player object, yet modify it properly when you need to.

overloading operator<< not working

Im having trouble outputting the data members of a Card object using the overloaded operator<<
I'm getting an error that says
"JS::operator<<(std::__1::basic_ostream >&, JS::Card const&)", referenced from:
linker command failed with exit code 1 (use -v to see invocation)
//
//Main.cpp
#include "Card.h"
#include "Deck.h"
#include <iostream>
using std::cout;
using namespace JasonSteindorf;
int main(int argc, const char * argv[]) {
//Deck d;
//d.shuffle();
Card c(5,3); //5 of Clubs
Card c2; //Ace of Diamonds
cout << c; //not working ???????? should says 5 of Clubs
c.displayCard(); //works
return 0;
}
//
//Deck.h
#ifndef JS_DECK_H
#define JS_DECK_H
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
namespace JS {
//forward declaration
class Card;
class Deck {
public:
Deck();
void shuffle();
private:
vector<Card>cards;
};
}
#endif
//
//Deck.cpp
#include "Deck.h"
#include "Card.h"
#include <algorithm>
using std::random_shuffle;
#include <iostream>
using std::cout;
using namespace JS;
Deck::Deck() {
cout << "A DECK OF CARDS!!!\n\n";
for(int suit = 0; suit < 4; suit++) {
for(int rank = 1; rank < 14; rank++) {
cards.push_back(Card(rank, suit));
}
cout << '\n';
}
}
void
Deck::shuffle() {
random_shuffle(cards.begin(), cards.end());
//for(int s = 0; s < 52; s++)
// cards.at(s)->displayCard();
for(vector<Card>::iterator it = cards.begin(); it < cards.end(); it++) {
Card a = *it;
a.displayCard();
}
}
//
//Card.h
#ifndef JS_CARD_H
#define JS_CARD_H
#include <iostream>
using std::ostream;
#include <string>
using std::string;
#include <vector>
using std::vector;
namespace JS {
class Card {
public:
enum Suit { DIAMONDS, HEARTS, SPADES, CLUBS };
enum Rank { ACE = 1, JACK = 11, QUEEN = 12, KING = 13 };
Card();
Card(int rank, int suit);
string getRank() const;
string getSuit() const;
int getRankValue() const;
int operator+(const Card& rhs);
void displayCard() const;
private:
int rank;
int suit;
};
//ostream &operator<<(ostream &out, const Card &rhs);
ostream& operator << (ostream& out, const Card& c);
}
#endif
//
//Card.cpp
#include "Card.h"
#include <iomanip>
using std::setw;
using std::right;
#include <iostream>
using std::cout;
#include <sstream>
using std::stringstream;
using namespace JS;
Card::Card(): rank(1), suit(0){
displayCard();
}
Card::Card(int rank, int suit) : rank(rank), suit(suit) {
displayCard();
}
string
Card::getSuit() const {
switch (suit) {
case SPADES: return "Spades"; break;
case HEARTS: return "Hearts"; break;
case DIAMONDS: return "Diamonds"; break;
case CLUBS: return "Clubs"; break;
default: return ""; break;
}
}
string
Card::getRank() const {
switch (rank) {
case ACE: return "Ace"; break;
case JACK: return "Jack"; break;
case QUEEN: return "Queen"; break;
case KING: return "King"; break;
default:
stringstream out;
out << rank;
return out.str();
break;
}
}
int
Card::getRankValue() const {
switch (rank) {
case ACE: return 1; break;
case JACK:
case QUEEN:
case KING: return 10; break;
default: return rank; break;
}
}
int
Card::operator+(const Card& rhs) {
return (getRankValue() + rhs.getRankValue());
}
ostream& operator <<(ostream& out, const Card& c)
{
out << c.getRank() << " of " << c.getSuit();
return out;
}
/*ostream
&operator<<(ostream &out, const Card &rhs) {
out << rhs.getRank() << " of " << rhs.getSuit();
return out;
}*/
void
Card::displayCard() const {
cout << right << setw(5) << getRank()
<< setw(3) << " of "
<< getSuit() << '\n';
}
Card.h declares the operator in a namespace:
namespace JS {
ostream& operator << (ostream& out, const Card& c);
}
but Card.cpp defines a different operator in the global namespace:
ostream& operator <<(ostream& out, const Card& c) {...}
Your choices are:
Put the declaration in the global namespace; or
Put the definition in the JS namespace; or
Qualify the name as JS::operator<< in the definition.

cannot swap objects in an array in C++

i am new to C++ and stuck in the swap stuff
the code below is a program of sort employee names in alphbetical order and print out the orginal one and sorted one ,but the
swap method doesn't work
the two output of printEmployees is excatly the same, can anyone help me? thx
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
class employee
{
/* Employee class to contain employee data
*/
private:
string surname;
double hourlyRate;
int empNumber;
public:
employee() {
hourlyRate = -1;
empNumber = -1;
surname = "";
}
employee(const employee &other) :
surname(other.surname),
hourlyRate(other.hourlyRate),
empNumber(other.empNumber){}
void setEmployee(const string &name, double rate,int num);
string getSurname() const;
void printEmployee() const;
employee& operator = (const employee &other)
{employee temp(other);
return *this;}};
void employee::setEmployee(const string &name, double rate, int num) {
surname = name;
hourlyRate = rate;
empNumber = num;
}
string employee::getSurname() const { return surname; }
void employee::printEmployee() const {
cout << fixed;
cout << setw(20) << surname << setw(4) << empNumber << " " << hourlyRate << "\n";
}
void printEmployees(employee employees[], int number)
{
int i;
for (i=0; i<number; i++) { employees[i].printEmployee(); }
cout << "\n";
}
void swap(employee employees[], int a, int b)
{
employee temp(employees[a]);
employees[a] = employees[b];
employees[b] = temp;
}
void sortEmployees(employee employees[], int number)
{
/* use selection sort to order employees,
in employee
name order
*/
int inner, outer, max;
for (outer=number-1; outer>0; outer--)
{
// run though array number of times
max = 0;
for (inner=1;
inner<=outer; inner++)
{
// find alphabeticaly largest surname in section of array
if (employees
[inner].getSurname() < employees[max].getSurname())
max = inner;
}
if (max != outer)
{
//
swap largest with last element looked at in array
swap(employees, max, outer);
}
}
}
int main()
{
employee employees[5];
employees[0].setEmployee("Stone", 35.75, 053);
employees[1].setEmployee
("Rubble", 12, 163);
employees[2].setEmployee("Flintstone", 15.75, 97);
employees[3].setEmployee("Pebble", 10.25, 104);
employees[4].setEmployee("Rockwall", 22.75, 15);
printEmployees(employees, 5);
sortEmployees(employees,5);
printEmployees(employees, 5);
return 0;
}
This code is broken:
employee& operator = (const employee &other)
{employee temp(other);
return *this;}
It should be something like:
employee& operator= (const employee &other)
{
surname = other.surname;
hourlyRate = other.hourlyRate;
empNumber = other.empNumber;
return *this;
}
As told by others, fixing your assignment operator will solve the problem.
I see that you tried to implement operator= in terms of copy constructor but missed to do a swap. You can try the below approach if you want to avoid code duplication in your copy constructor and assignment operator.
employee& operator=(const employee& other)
{
employee temp(other);
swap(temp);
return *this;
}
void swap(employee& other)
{
std::swap(surname, other.surname);
std::swap(hourlyRate, other.hourlyRate);
std::swap(empNumber, other.empNumber);
}

Pointer to dynamic array of pointers to objects

Card class header
class card {
public:
string rtn_suit() { return suit; }
int rtn_rank() { return rank; }
void set_suit(string new_suit){ suit = new_suit; }
void set_rank(int new_rank) { rank = new_rank; }
card();
card(string suit, int rank);
card(const card& copyCARD);
~card();
private:
string suit;
int rank;
};
#endif
card.cpp
#include "card.h"
card::card()
{
set_suit("default");
set_rank(0);
}
card::card(string new_suit, int new_rank)
{
// allows for using private class member variables
set_suit(new_suit); // can be anything (string)
set_rank(new_rank); // anticipating simple number ranking (int)
}
card::~card() {}
Deck class header
class deck {
public:
static const int default_cap = 52;
void addCard(card *new_card);
deck & operator=(const deck &sourceDECK);
void deckPrint();
// ----------------------------------------------------
deck(int init_cap = default_cap);
deck(const deck& sourceDECK);
~deck(){ delete [] decklist ; }
private:
card *decklist;
int used;
int capacity;
};
#endif
deck class
deck::deck(int init_cap)
{
card **decklist = new card*[init_cap];
for(int i=0;i<init_cap;i++)
{
decklist[i]=new card;
}
capacity = init_cap;
used=0;
}
deck::deck(const deck& sourceDECK)
{
card **newDECK;
if (capacity != sourceDECK.capacity)
{
newDECK = new card*[sourceDECK.capacity];
for(int i=0;i<sourceDECK.capacity;i++) { newDECK[i]=new card(); }
decklist = /*reinterpret_cast<card*>(*/newDECK/*)*/;
capacity = sourceDECK.capacity;
}
used = sourceDECK.used;
copy(sourceDECK.decklist, sourceDECK.decklist+ used, decklist);
}
deck& deck::operator= (const deck& sourceDECK)
{
if (this == &sourceDECK)
return *this;
card ** newDECK;
if (capacity != sourceDECK.capacity)
{
newDECK = new card*[sourceDECK.capacity];
for(int i=0;i<sourceDECK.capacity;i++) { newDECK[i]=new card(); }
for (int i=0; i<capacity; i++) { delete &decklist[i]; }
delete [ ] decklist;
decklist = /*reinterpret_cast<card*>(*/newDECK/*)*/;
capacity = sourceDECK.capacity;
}
// Copy the data from the source array:
used = sourceDECK.used;
copy(sourceDECK.decklist, sourceDECK.decklist + used, decklist);
return *this;
}
void deck::addCard(card* new_card)
{
//------- Not using vectors----
//deckList.push_back(new_card);
//cout << "Card added."<<endl;
decklist[used] = new_card;
//decklist[used].set_rank(new_card->rtn_rank());
//decklist[used].set_suit(new_card->rtn_suit());
++used;
cout << "Card added."<<endl;
}
void deck::deckPrint()
{
if ( capacity > 0 )
{
for(int i = 0; i < capacity; i++)
{
cout << "----------"<<endl;
cout << decklist[i].rtn_rank() << " ";
cout << decklist[i].rtn_suit() << endl;
cout << "----------"<<endl;
}
}
else\
{
cout << "There are no cards in the deck."<<endl;
}
}
And lastly a main()
int main ()
{
string new_suit, del_suit;
int new_rank, del_rank;
deck newDeck;
card *temp_card;
cout<<"Enter the card's suit: ";
cin>>new_suit;
cout<<endl<<"Enter the card's rank: ";
cin>>new_rank;
cin.clear();
cin.ignore(1000, '\n');
temp_card = new card(new_suit, new_rank);
newDeck.addCard(temp_card);
newDeck.deckPrint();
return 0;
}
Somewhere, somehow I am not initializing or allocating properly. Or maybe I screwed up the pointers....
As is, will not compile due to:
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'card *' (or there is no acceptable conversion)
\projects\cards\cards\card.h(27): could be 'card &card::operator =(const card &)' while trying to match the argument list '(card, card *)'
If I use (currently commented out) a 'deeper copy' aka:
decklist[used].set_rank(new_card->rtn_rnk());
it will throw the error in deckPrint()
I originally wrote this with vectors for a simple card class implementation and then we started learning about dynamic arrays - and I got the bright idea to try and throw pointers in the mix. Again, this is not homework - this is for personal growth.
If there is a tutorial out there that I missed which clearly outlines what I am trying to do, feel free to point me towards that also - I have poured over the top 30 google results and tons of posts here. Half the time people recommend using vectors, which again is not my goal.
Thanks for your time, I know it is lengthy.
I think you have a small bug in your deck class construction function.
deck::deck(int init_cap)
{
card **decklist = new card*[init_cap];
for(int i=0;i<init_cap;i++)
{
decklist[i]=new card;
}
}
here card **decklist is a new pointer to pointer, I guess you want to initialize the private variable decklist.
so you may change it to
deck::deck(int init_cap)
{
decklist = new card*[init_cap];
decklist here is the private variable.
and change the declaration
private:
card **cardlist;