I am defining my own string class called StringSet using a vector of strings. I am assigned to overload the >>, <<, ==, >, >=, +, += and * operators, and ran into a problem with <<. The output should be:
Welcome to stringset
hi everyone
"all" does not exist in the set.
hi
But it seems to be skipping the second and third lines. I am very new to overloading operators, so I am probably overlooking an obvious mistake.
header and class declaration:
#include <iostream>
#include <vector>
#include<string>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;
class StringSet
{
public:
//Constructor
StringSet();
//Copy Constructor
StringSet(const StringSet& s);
//Default constructors
StringSet(string initialStrings[], const int ARRAYSIZE);
//Destructor
~StringSet();
void add(const string s);
void remove(const string s);
//Returns length
int size()
{
return length;
}
// Overload the << operator so that it outputs the strings
friend ostream& operator <<(ostream& outs, const StringSet& s);
private:
//size of the vector
int length;
// Vector to store strings
vector <string> data;
};
function definitions:
ostream& operator<<(ostream& outs, const StringSet& s)
{
outs << "\n";
for (int i = 0; i < s.length; i++)
{
outs << s.data[i] << " ";
}
outs << "\n";
return outs;
}
//Add a string to the vector
void StringSet::add(const string s)
{
bool c = check(s);
if (c == false)
{
data.push_back(s);
}
else
{
cout << "\"" << s << "\" already exists in the set.";
}
}
// Remove a string from the vector
void StringSet::remove(const string s)
{
bool c = check(s);
if (c == true)
{
vector<string>::iterator position = search(s);
data.erase(position);
}
else
{
cout << "\"" << s << "\" does not exist in the set\n";
}
}
StringSet::StringSet()
{
length = 0;
}
StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
for (int i = 0; i < data.size(); i++)
{
initialStrings[i] = " ";
}
}
// Copy constructor
StringSet::StringSet(const StringSet& s)
{
for (int i = 0; i < data.size(); i++)
{
data[i] = s.data[i];
}
}
StringSet::StringSet()
{
length = 0;
}
StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
for (int i = 0; i < data.size(); i++)
{
initialStrings[i] = " ";
}
}
// Copy constructor
StringSet::StringSet(const StringSet& s)
{
for (int i = 0; i < data.size(); i++)
{
data[i] = s.data[i];
}
}
// Check if a string exists in the vector
bool StringSet::check(const string s)
{
vector<string>::iterator it = find(data.begin(), data.end(), s);
if (it != data.end())
{
return true;
}
else
{
return false;
}
}
Main function:
int main()
{
ofstream outs;
ifstream ins;
StringSet doc1, doc2, query
cout << "Welcome to stringset\n";
doc1.add("hi");
doc1.add("everyone");
outs << doc1;
doc1.remove("everyone");
doc1.remove("all");
outs << doc1;
}
If you use a variable that stores the size of the set, you should increment/decrement it when adding/removing elements. You can also change the definition of the StringSet::size():
int size() const
{
return static_cast<int>(data.size());
}
I don't know if this has happened to some of you guys. I haven't started programming because "I don't know where to start". I want to make a platform video game, and 8 bits one. Yeah it will take a lot of time and skill, but I always like to jump to the complicated stuff.
I'm the kind of person that likes to use the latest of the latest programs. So I use Visual Studio 2017, however SFML is up to VS2015. Is there a way to use SFML is VS2017? What can I do?
First, congrats on starting your journey into programming!
However, as someone who has tutored many kids who have the same ambition (e.g. learning C++ to make a video game), I'd recommend you start down a simpler path.
I won't go into trying to learn C# or Java or some other language, as I, and many others, actually started with C; it's not about learning the particular language, it's about understanding the system as a whole. The concept of a thread, object, loops or functions doesn't change, it's how it's utilized that changes between languages.
I'm the kind of person that likes to use the latest of the latest programs.
While this might typically be good for most programs, due to bug fixes or other enhancements, this is not true for development environments. When you update Visual Studio, you're typically updating your entire toolchain: compiler, linker, SDK's, etc.
This means the possibility to introduce either a buggy compiler, or have code flagged as deprecated, among other issues to be considered. Especially when developing something like a game.
I haven't started programming because "I don't know where to start"
Here's a simple "war" card game that emulates 2 players; it automatically plays war until the game is won. It repeats this until an interrupt signal is received (CTRL+C) and it prints out the maximum number of turns during any game, as well as the minimum number of turns in any game played by our 'auto-players'.
It's in C++, can be modified to take user input for a blackjack or poker game, and you can build it on any system simply enough.
This code is meant for teaching, so you can take this code, modify it, build it, run it, and understand what's happening in each of those steps.
From there, you can learn more, ask more questions, and eventually you'll be able to make your 2D platform game with SFML.
war.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <deque>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <csignal>
#define print(v) std::cout << v
#define printl(v) std::cout << v << std::endl
namespace util {
class random {
public:
random() { std::srand(std::time(0)); }
int get(int max_val) { return std::rand() % max_val; }
};
}
namespace battle {
class suit {
public:
typedef enum enum_t {
HEART,
DIAMOND,
CLUB,
SPADE,
END
} enum_t;
suit() : m_val(END) {}
suit(const suit& cp) : m_val(cp.m_val) {}
explicit suit(enum_t val) : m_val(val) {}
suit& operator=(const suit& other)
{
this->m_val = other.m_val;
return *this;
}
suit& operator=(const enum_t& other)
{
this->m_val = other;
return *this;
}
bool operator==(const enum_t& other) { return (this->m_val == other); }
bool operator!=(const enum_t& other) { return (this->m_val != other); }
bool operator<(const enum_t& other) { return (this->m_val < other); }
bool operator>(const enum_t& other) { return (this->m_val > other); }
operator int() const { return static_cast<int>(this->m_val); }
operator enum_t() const { return this->m_val; }
friend std::ostream& operator<<(std::ostream& os, const battle::suit& val)
{
switch (val.m_val) {
case battle::suit::HEART: os << "♥"; break;
case battle::suit::DIAMOND: os << "♦"; break;
case battle::suit::CLUB: os << "♣"; break;
case battle::suit::SPADE: os << "♠"; break;
default: os << '?'; break;
}
return os;
}
private:
enum_t m_val;
};
class value {
public:
typedef enum enum_t {
ACE,
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
JACK,
QUEEN,
KING,
END
} enum_t;
value() : m_val(END) {}
value(const value& cp) : m_val(cp.m_val) {}
explicit value(enum_t val) : m_val(val) {}
value& operator=(const value& other)
{
this->m_val = other.m_val;
return *this;
}
value& operator=(const enum_t& other)
{
this->m_val = other;
return *this;
}
bool operator==(const enum_t& other) { return (this->m_val == other); }
bool operator!=(const enum_t& other) { return (this->m_val != other); }
bool operator<(const enum_t& other) { return (this->m_val < other); }
bool operator>(const enum_t& other) { return (this->m_val > other); }
operator int() const { return static_cast<int>(this->m_val); }
operator enum_t() const { return this->m_val; }
friend std::ostream& operator<<(std::ostream& os, const battle::value& val)
{
switch (val.m_val) {
case battle::value::ACE: os << 'A'; break;
case battle::value::JACK: os << 'J'; break;
case battle::value::QUEEN: os << 'Q'; break;
case battle::value::KING: os << 'K'; break;
default: os << static_cast<int>(val); break;
}
return os;
}
private:
enum_t m_val;
};
class card {
public:
card() : m_val(value::END), m_suit(suit::END) {}
card(const card& cp) : m_val(cp.m_val), m_suit(cp.m_suit) {}
card(int suit, int val) : m_val(static_cast<value::enum_t>(val)), m_suit(static_cast<suit::enum_t>(suit)) {}
card(suit::enum_t suit, value::enum_t val) : m_val(val), m_suit(suit) {}
~card() {}
card& operator=(const card& other)
{
this->m_val = other.m_val;
this->m_suit = other.m_suit;
return *this;
}
bool operator==(const card& other)
{
return (this->m_val == other.m_val && this->m_suit == other.m_suit);
}
bool operator!=(const card& other)
{
return !(this->m_val == other.m_val && this->m_suit == other.m_suit);
}
bool operator<(const card& other)
{
if (this->m_val == value::ACE) {
return false;
}
return (this->m_val < other.m_val);
}
bool operator>(const card& other)
{
if (this->m_val == value::ACE) {
return (other.m_val != value::ACE);
}
return (this->m_val > other.m_val);
}
bool empty() const
{
return (this->m_val == value::END ||
this->m_suit == suit::END);
}
friend std::ostream& operator<<(std::ostream& os, const card& obj)
{
os << obj.m_val << obj.m_suit;
return os;
}
int suit() const
{
return this->m_suit;
}
value::enum_t value() const
{
return this->m_val;
}
private:
battle::value m_val;
battle::suit m_suit;
};
class deck {
public:
static const std::size_t DECK_SIZE = 52;
static const std::size_t HALF_DECK = 26;
deck() : m_rand(), m_deck() {}
~deck() {}
bool add(card& c)
{
if (c.empty()) { return false; }
const std::size_t idx = static_cast<std::size_t>(c.suit());
itr_t cv = std::find(this->m_deck.begin(), this->m_deck.end(), c);
bool found = (cv != this->m_deck.end());
if (!found) {
this->m_deck.insert(this->m_deck.begin(), c);
return true;
}
return false;
}
void add_init(card c)
{
const std::size_t idx = static_cast<std::size_t>(c.suit());
this->m_deck.push_back(c);
}
card deal()
{
if (!this->empty()) {
std::size_t cnt = this->m_deck.size();
if ((cnt == 0) || ((cnt - 1) == 0)) {
card ret(this->m_deck[0]);
this->m_deck.erase(this->m_deck.begin());
return ret;
}
cnt = this->m_rand.get(cnt);
card ret = this->m_deck[cnt];
this->remove_it(ret);
return ret;
}
return card();
}
bool empty() const
{
return this->m_deck.empty();
}
void fill()
{
printl("Filling deck");
for (int s = suit::HEART; s < suit::END; ++s) {
for (int v = value::ACE; v < value::END; ++v) {
this->add_init(battle::card(s, v));
}
}
}
void top_to_back()
{
card& c = this->m_deck[this->m_deck.size()-1];
for (itr_t s = this->m_deck.begin(); s != this->m_deck.end(); ++s) {
if ((*s) == c) {
this->m_deck.erase(s);
break;
}
}
this->m_deck.insert(this->m_deck.begin(), c);
}
void remove(const card& c)
{
if (!this->empty()) {
this->remove_it(c);
}
}
std::size_t size() const
{
return this->m_deck.size();
}
card operator[](std::size_t idx) const
{
return this->m_deck[idx];
}
private:
deck(const deck& cp); // = delete
deck& operator=(const deck& other); // = delete
util::random m_rand;
std::deque<card> m_deck;
typedef std::deque<card>::iterator itr_t;
void remove_it(const card& c)
{
for (itr_t s = this->m_deck.begin(); s != this->m_deck.end(); ++s) {
if ((*s) == c) {
this->m_deck.erase(s);
break;
}
}
}
};
class player {
public:
player() : m_hand(), m_name("NaN"), m_id(), m_tot_add(0), m_tot_rem(0), m_won(0), m_other(0) {}
player(std::size_t id) : m_hand(), m_name(), m_id(id), m_tot_add(0), m_tot_rem(0), m_won(0), m_other(0)
{
std::stringstream ss;
ss << "Player " << id;
this->m_name = ss.str();
}
void add_init(card c)
{
this->m_hand.add_init(c);
}
bool add_card(card c)
{
++this->m_tot_add;
return this->m_hand.add(c);
}
void add_cards(const std::deque<card>& cards)
{
std::deque<card>::const_iterator start = cards.begin();
while (start != cards.end()) {
this->add_card(*start);
++start;
}
}
bool empty() const
{
return this->m_hand.empty();
}
std::deque<card> battle_group() const
{
std::deque<card> ret;
if (!this->empty()) {
std::size_t top_idx = this->m_hand.size()-1;
for (std::size_t i = 0; i < 4 && top_idx > 0; ++i) {
ret.push_back(this->m_hand[--top_idx]);
}
}
return ret;
}
std::size_t hand_size() const
{
return this->m_hand.size();
}
std::size_t id() const
{
return this->m_id;
}
std::string name() const
{
return this->m_name;
}
void print_hand() const
{
for (std::size_t i = 0; i < this->m_hand.size(); ++i) {
std::cout << this->m_hand[i] << std::endl;
}
}
void remove_card(card c)
{
++this->m_tot_rem;
this->m_hand.remove(c);
}
void remove_cards(const std::deque<card>& cards)
{
std::deque<card>::const_iterator start = cards.begin();
while (start != cards.end()) {
this->remove_card(*start);
++start;
}
}
void print_stats()
{
printl("---" << this->name() << "---");
printl("Hand: " << this->m_hand.size());
printl("Wins: " << this->m_won);
printl("Took: " << this->m_tot_add);
printl("Lost: " << this->m_tot_rem);
}
void set_other_play(player& other)
{
this->m_other = &other;
}
void takes(card& c)
{
printl(this->m_name << " takes " << c);
this->m_hand.top_to_back();
this->m_other->remove_card(c);
this->add_card(c);
}
card top_card() const
{
if (this->empty()) { return card(); }
return this->m_hand[this->m_hand.size()-1];
}
void won_battle(card& c)
{
printl(this->m_name << " won the battle!");
this->takes(c);
++this->m_won;
}
void won_battle(const std::deque<card>& cards)
{
std::deque<card>::const_iterator start = cards.begin();
this->m_hand.top_to_back();
print(this->m_name << " won the battle, takes");
while (start != cards.end()) {
print(" " << *start);
this->m_other->remove_card(*start);
this->add_card(*start);
++start;
}
printl("");
++this->m_won;
}
private:
deck m_hand;
std::string m_name;
std::size_t m_id;
std::size_t m_tot_add;
std::size_t m_tot_rem;
std::size_t m_won;
player* m_other;
};
class game {
public:
game() : m_deck(), m_p1(1), m_p2(2), m_turns(0), m_battles(0)
{
this->m_p1.set_other_play(this->m_p2);
this->m_p2.set_other_play(this->m_p1);
this->m_deck.fill();
printl("Dealing cards");
for (std::size_t i = 0; i < deck::HALF_DECK; ++i) {
this->m_p1.add_init(this->m_deck.deal());
this->m_p2.add_init(this->m_deck.deal());
}
}
std::size_t dobattle(battle::card& c1, battle::card& c2)
{
printl("BATTLE!!!!");
++this->m_battles;
std::size_t sz1 = this->m_p1.hand_size();
std::size_t sz2 = this->m_p2.hand_size();
if (sz2 <= 1 && sz1 > 1) {
this->m_p1.won_battle(c2);
return this->m_p1.id();
}
if (sz1 <= 1 && sz2 > 1) {
this->m_p2.won_battle(c1);
return this->m_p2.id();
}
std::deque<battle::card> t1 = this->m_p1.battle_group();
std::deque<battle::card> t2 = this->m_p2.battle_group();
printl(this->m_p1.name() << ": " << t1.back() << ", " << this->m_p2.name() << ": " << t2.back());
if (t1.back() > t2.back()) {
this->m_p1.won_battle(t2);
return this->m_p1.id();
} else if (t1.back() < t2.back()) {
this->m_p2.won_battle(t1);
return this->m_p2.id();
} else { // another battle
this->m_p1.remove_card(c1); this->m_p1.remove_cards(t1);
this->m_p2.remove_card(c2); this->m_p2.remove_cards(t2);
if (this->dobattle(t1.back(), t2.back()) == this->m_p1.id()) {
this->m_p1.add_card(c1); this->m_p1.add_cards(t1);
this->m_p2.add_card(c2); this->m_p2.add_cards(t2);
this->m_p1.won_battle(t2);
return this->m_p1.id();
} else {
this->m_p1.add_card(c1); this->m_p1.add_cards(t1);
this->m_p2.add_card(c2); this->m_p2.add_cards(t2);
this->m_p2.won_battle(t1);
return this->m_p2.id();
}
}
return 0;
}
void play()
{
battle::card c1, c2;
while (true) {
if (this->check_win()) break;
c1 = this->m_p1.top_card();
c2 = this->m_p2.top_card();
printl(this->m_p1.name() << ": " << c1 << ", " << this->m_p2.name() << ": " << c2);
if (c1 < c2) {
this->m_p2.takes(c1);
} else if (c1 > c2) {
this->m_p1.takes(c2);
} else { // c1 == c2
this->dobattle(c1, c2);
}
++this->m_turns;
if (this->check_win()) break;
}
printl("");
printl("Game over!");
printl("");
}
void print_stats()
{
printl("----Stats----");
printl("Turns: " << this->m_turns);
printl("Battles: " << this->m_battles);
this->m_p1.print_stats();
this->m_p2.print_stats();
}
std::size_t turns() const { return this->m_turns; }
std::size_t battles() const { return this->m_battles; }
private:
deck m_deck;
player m_p1;
player m_p2;
std::size_t m_turns;
std::size_t m_battles;
bool check_win() const
{
if (this->m_p1.empty() || this->m_p2.empty()) {
if (this->m_p1.empty() && !this->m_p2.empty()) {
printl(this->m_p2.name() << " WINS!");
} else if (!this->m_p1.empty() && this->m_p2.empty()) {
printl(this->m_p1.name() << " WINS!");
} else {
printl("TIE?");
}
return true;
}
return false;
}
};
}
static volatile bool m_stop;
static void sig_hand(int sig) {
if (sig == SIGINT) { m_stop = true; }
}
int main(int argc, char* argv[])
{
std::size_t x = ~0;
std::size_t n = 0;
std::size_t g = 0;
const std::size_t MAX = 8; // 7*4 = 28
std::signal(SIGINT, sig_hand);
while ((x > MAX) && !m_stop) {
battle::game game;
game.play();
++g;
game.print_stats();
if (game.turns() < x) {
x = game.turns();
std::cerr << "least: " << x << std::endl;
}
if (n < game.turns()) {
n = game.turns();
std::cerr << "most: " << n << std::endl;
}
}
//printl("Done! Games played: " << g << ", Least turns: " << x << ", Most turns: " << n);
std::cerr << "Done! Games played: " << g << ", Least turns: " << x << ", Most turns: " << n << std::endl;
return 0;
}
Hope that can help.
Just a note to say SFML now works fine with VS2017.
I have version 2.5 binaries no need to compile.
See instructions here:
https://www.sfml-dev.org/tutorials/2.5/start-vc.php
I implementing vector. so i test operators, but operator+ is not working correctly.
hereis header MyDoubleVector.h
class MyDoubleVector {
public:
MyDoubleVector();
MyDoubleVector(size_t init_capacity);
MyDoubleVector(const MyDoubleVector& v);
~MyDoubleVector();
MyDoubleVector& operator=(const MyDoubleVector& v); //for deep copy
bool operator==(const MyDoubleVector& v); //binary
MyDoubleVector& operator+=(const MyDoubleVector& add);
MyDoubleVector operator[](int index); //return reference to data that requested index
MyDoubleVector operator+(const MyDoubleVector& rhs); //binary
MyDoubleVector operator-(const MyDoubleVector& rhs); //binary
MyDoubleVector operator*(const MyDoubleVector& rhs); //binary
MyDoubleVector operator-(); //unary
MyDoubleVector operator()(); //unary
void pop_back();
void push_back(double x);
size_t capacity() const;
size_t size() const;
void reserve(size_t n);
bool empty() const;
void clear();
void print_info();
private:
double *data;
size_t capa;
size_t used;
};
and here is implement code "MyDoubleVector.cpp"
MyDoubleVector MyDoubleVector::operator+(const MyDoubleVector &rhs) { //binary
//pre : same size,
//poset : return sum,
if (capa != rhs.capa) {
exit(1);
}
MyDoubleVector tmp(capa);
for (size_t i = 0; i < capa; i++) {
tmp.data[i] = data[i] + rhs.data[i];
}
return tmp;
};
and main code is
int i = 0;
MyDoubleVector v1(3);
for (i = 0; i < 4; i++) {
v1.push_back(i);
}
cout << "v1" << endl;
v1.print_info();
MyDoubleVector v2(3);
for (i = 0; i < 4; i++) {
v2.push_back(i * 10);
}
cout << "v2" << endl;
v2.print_info();
cout << "(v1+v2)" << endl;
(v1+v2).print_info();
output is
v1
0 1 2 3
used : 4, capa : 4
v2
0 10 20 30
used : 4, capa : 4
(v1+v2)
-6.27744e+66 -6.27744e+66 -6.27744e+66 -6.27744e+66
used : 0, capa : 4
i think retruned tmp is freed when print_info() function executed.
how print vector correctly?
You aren't setting the used of the return vector. Without seeing the rest of the implementation of the class, I guess you can change to:
MyDoubleVector MyDoubleVector::operator+(const MyDoubleVector &rhs) { //binary
//pre : same size,
//poset : return sum,
if (capa != rhs.capa) {
exit(1);
}
MyDoubleVector tmp(capa);
for (size_t i = 0; i < capa; i++) {
tmp.push_back(data[i] + rhs.data[i]);
}
return tmp;
};
im working on a little scrabblegame which i read a txtfile and create a hashtable for all words inside. Word is a specific class which contains a vector of .
i want to create a hashmap by my own and define the length of my "Dictionary" is 50000. im using a nullpointer to reserve all index of my array. If i want to print to my hashtable, compiler tells me a segmentation fault. does any one seems the error?
the headerfile:
class Dictionary {
public:
Dictionary();
Dictionary(string filepath);
friend std::ostream& operator<<(std::ostream& os, const Dictionary& obj);
bool find(const Word& word);
vector<Word> allPossibleWords(const vector<Character>& tiles);
// struct compare {
//
// bool operator()(const Word& a, const Word& b) {
// return a.operator<(b);
// }
// } myCompare;
vector<Word> m_allWords;
vector<Word>::iterator itVecWords;
static const int table_size = 500000;
// std::array <Word*, table_size> arrWords = {nullptr};
Word* arrWords[table_size] = {nullptr};
int hash(Word new_word);
void addItem(Word word);
void printHashTable();
the cpp:
Dictionary::Dictionary(string filepath) {
ifstream datei(filepath.c_str());
while (datei.good() && !datei.eof()) {
string temp;
string temp1;
string::size_type pos;
getline(datei, temp);
pos = temp.find(" ");
temp1 = temp.substr(0, pos);
Word new_word(temp1);
addItem(new_word);
}
datei.close();
}
std::ostream& operator<<(std::ostream& os, const Dictionary& obj) {
for (int i = 0; i < obj.m_allWords.size(); i++) {
os << obj.m_allWords[i] << endl;
}
return os;
}
bool Dictionary::find(const Word& word) const {
if (std::binary_search(m_allWords.begin(), m_allWords.end(), word)) {
return true;
}
return false;
}
vector<Word> Dictionary::allPossibleWords(const vector<Character>& tiles) const {
vector<Word> ergebnis;
string tmp;
int cnt = 0;
for (int i = 0; i < tiles.size(); i++) {
tmp += tiles[i].GetC();
}
sort(tmp.begin(), tmp.end());
for (int i = 1; i <= tiles.size(); i++) {
do {
string piece = tmp.substr(0, i);
do {
Word search = Word(piece);
//Überschreibt immer der in Ergebnis existierte Wert
if (find(search) && std::find(ergebnis.begin(), ergebnis.end(), search) == ergebnis.end()) {
ergebnis.push_back(search);
}
} while (next_permutation(piece.begin(), piece.end()));
} while (next_permutation(tmp.begin(), tmp.end()));
}
return ergebnis;
}
int Dictionary::hash(Word new_word) {
int index = 0;
for (auto u : new_word.new_Character) {
index += (int) u.GetC();
}
index = index * (int) new_word.new_Character.at(0).GetC();
index = index * (int) new_word.new_Character.at(new_word.new_Character.size() - 1).GetC();
return index % table_size;
}
void Dictionary::addItem(Word word) {
int index = hash(word);
if (arrWords[index] == nullptr) {
arrWords[index] = new Word(word);
} else {
Word* ptr = arrWords[index];
Word* neu = new Word(word);
while (ptr->getNextWord() != nullptr) {
ptr = ptr->getNextWord();
}
ptr->setNextWord(neu);
}
}
void Dictionary::printHashTable() {
Word* tmp;
for (int i = 0; i < table_size; i++) {
tmp = arrWords[i];
if (tmp != nullptr) {
tmp->printWord();
cout << "Index : " << i;
}
tmp = tmp->getNextWord();
}
}
class Word {
public:
Word();
Word(string m_wort);
int length() const;
int points() const;
friend std::ostream& operator<<(std::ostream& os, const Word& obj);
bool operator==(const Word& right) const; /
bool operator!=(const Word& right) const;
bool contains(const Character& c) const;
Word substr(int start, int end) const;
bool operator<(const Word& right) const;
vector <Character> new_Character;
Word* Next = nullptr;
void setNextWord(Word*);
Word* getNextWord();
void printWord();
string getWordAsString();
CPP File:
void Word::setNextWord(Word* w) {
Next = w;
}
Word* Word::getNextWord() {
return Next;
}
void Word::printWord() {
string s = "";
for (int i = 0; i < new_Character.size(); i++) {
s += new_Character.at(i).GetC();
}
cout << s << endl;
}
string Word::getWordAsString() {
string s;
for (int i = 0; i < new_Character.size(); i++) {
s += new_Character.at(i).GetC();
}
return s;
}
The program compiles just fine but when the output window comes up, it shows the elements i've outputed and then i hear a windows sound, and then it just stops.
I'm trying to enqueue elements into the circular queue, and it appears that they are being input just fine since the display function prints them out. Everything seems to make sense, but the program just sorta crashes, could anybody elaborate on why exactly it might be doing this? My code is below :
#include <iostream>
#include <algorithm>
using namespace std;
template<class QueueElement>
class dynamic_queue
{
public:
dynamic_queue(int = 10);
dynamic_queue(const dynamic_queue &);
~dynamic_queue();
QueueElement *getHead();
int getSize() const;
bool isEmpty()const;
int getCapacity();
void display(ostream &out) const;
void enqueue(const QueueElement &value);
void dequeue();
bool swap(dynamic_queue &, dynamic_queue &);
void clear();
const dynamic_queue & operator=(const dynamic_queue &);
friend ostream & operator<< <> (ostream &, const
dynamic_queue<dynamic_queue> &);
private:
int ihead;
int itail;
int initial_capacity;
int array_capacity;
int array_size;
QueueElement *myarray;
};
template<class QueueElement>
dynamic_queue<QueueElement>::dynamic_queue(int n)
:ihead(0),itail(0)
{
if (n <= 0)
{
initial_capacity = 1;
}
else
{
initial_capacity = max(n, 1);
}
array_capacity = initial_capacity;
myarray = new QueueElement(initial_capacity);
array_size = initial_capacity;
}
template<class QueueElement>
dynamic_queue<QueueElement>::~dynamic_queue()
{
delete[]myarray;
}
template<class QueueElement>
void dynamic_queue<QueueElement>::enqueue(const QueueElement &inserted_value
)
{
int newTail = (itail + 1) % array_capacity;
if (newTail != ihead)
{
myarray[itail] = inserted_value;
itail = newTail;
}
else
{
cout << "Queue is full" << endl;
exit(1);
}
cout << "itail: " << itail << endl;
cout << "array size" << array_size << endl;
}
template<class QueueElement>
ostream & operator<<(ostream & o, const dynamic_queue<QueueElement> &output_elements)
{
o << output_elements;
return o;
}
template<class QueueElement>
void dynamic_queue<QueueElement>::display(ostream &out) const
{
for (int i = ihead;i != itail;i = (i + 1) % array_capacity)
{
out << myarray[i] << " ";
cout << endl;
}
}
template<class QueueElement>
int dynamic_queue<QueueElement>::getSize() const
{
int count = 0;
for (int i = 0;i <= array_capacity;i++)
{
count++;
}
return count;
}
main function:
#include <iostream>
#include "DynamicCircularQueue.h"
using namespace std;
int main()
{
dynamic_queue<int> queue1(5);
queue1.enqueue(10);
queue1.enqueue(11);
queue1.getSize();
queue1.display(cout);
}
myarray = new QueueElement(initial_capacity);
should be:
myarray = new QueueElement[initial_capacity];
Since queue-element is int, you were allocating an array of just one element, that is why your code crashed at the second call to enqueue.