Problem with throw exceptions when stack are empty ..... Queue / stack implementation - c++

I need to throw an exception when both stacks are empty but i dont know how I should write it.
I have to implement a queue with 2 stacks!
this is main
#include "QueueFromStacks.h"
int main()
{
/* THIS IS JUST TO SHOW YOU HOW #include <stack> WORKS
stack<int> st1;
stack<int> st2;
cout << "Size before push:" << st2.size() << "\n";
st2.push(2);
st2.push(5);
cout << "Size after two pushes:" << st2.size() << "\n";
cout << st2.top() << "\n";
st2.pop();
cout << "Size of st2 after one pop:" << st2.size() << "\n";
st1.push(st2.top());
st2.pop();
cout << "Size of st1:" <<st1.size()<< " Size of st2:"<< st2.size();
*/
QueueFromStacks<int> qfs;
qfs.QueueFromStacks();
qfs.enqueue(1);
qfs.enqueue(2);
qfs.enqueue(3);
qfs.dequeue();
cout << "Queue Front : " << (qfs.front())<< endl;
// You have to implement QueuefromStack
// The logic of the queue remains the same(FIFO) but you have to use the two stacks to store your elements
// In the main program create a queuefromstack object and use your implemented methods to clearly show us what u did
return 0;
}
HEADER FILE
#ifndef QUEUEFROMSTACKS_H_
#define QUEUEFROMSTACKS_H_
#include <iostream>
#include <stack>
#include <string>
using namespace std;
class QueueEmptyException{
public:
QueueEmptyException();
~QueueEmptyException();
string getMessage() { return "Queue is empty"; }
};
template <typename E>
class QueueFromStacks
{
public:
QueueFromStacks();
~QueueFromStacks();
int size() const;
bool empty() const;
const E& front() const throw(QueueEmptyException);
void enqueue (const E& e);
void dequeue() throw(QueueEmptyException);
private:
stack<E> st1;
stack<E> st2;
int numElements;
};
#endif /* QUEUEFROMSTACKS_H_ */
IMPLEMENTATION
#include "QueueFromStacks.h"
template <typename E>
QueueFromStacks<E>::QueueFromStacks()
{
numElements = 0;
}
template <typename E>
QueueFromStacks<E>::~QueueFromStacks()
{
// TODO Auto-generated destructor stub
}
template <typename E>
int QueueFromStacks<E>::size() const
{
return numElements;
}
template <typename E>
bool QueueFromStacks<E>::empty() const
{
return (size() == 0);
}
template <typename E>
const E& QueueFromStacks<E>::front() const
throw(QueueEmptyException)
{
return st2.top(); // don't forget to check for empty and throw exception if it is empty.
}
template <typename E>
void QueueFromStacks<E>::enqueue (const E& e)
{
st2.push(e);
numElements++;
}
template <typename E>
void QueueFromStacks<E>::dequeue()
throw(QueueEmptyException)
{
**// if both stacks are empty // here i dont know what should i put as a throw condition
if (st1.empty() && st2.empty())
{
throw;
}**
// if the second stack is empty, move elements from the first stack to it
if (st2.empty())
{
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
// or make a call to swap(s1, s2)
}
// return the top item from the second stack
int top = st2.top();
st2.pop();
numElements--;
}

You need to change this:
void QueueFromStacks<E>::enqueue (const E& e)
{
st2.push(e);
numElements++;
}
to this:
void QueueFromStacks<E>::enqueue (const E& e)
{
st1.push(e);
numElements++;
}

Related

c++ Template Class Syntax for Methods

I am learning templates and am struggling to set up my put method without compiler errors. Can someone point me in the right direction? The commented sections are not implemented yet, but based on an Integer-key, String-value implementation.
The concrete error I am having: Severity Code Description Project File Line Suppression State
Error C2923 'HashTable<int,std::string>::HashItem': 'key' is not a valid template type argument for parameter 'Key'
#pragma once
#include <cmath>
#include <iostream>
#include <list>
using namespace std;
template<typename Key, typename Value>
class HashTable
{
template<typename Key, typename Value>
class HashItem {
public:
Key key;
Value value = nullptr;
bool operator==(const HashItem& hi) const { return key == hi.key && value == hi.value; }
HashItem(const Key& k, const Value& v)
: key(k), value(v) {}
// for part b)
HashItem& operator=(const Value& v) {
this->value = v;
return *this;
}
operator string() { return this->value; }
};
list<HashItem<Key, Value>>* table;
int current_total = 0;
float FILL_LEVEL = 0.8; // Füllgrad, between 0 and 1
// not const:
int CAPACITY = 100; // default value
// for hash functions/preparing for use with strings:
const int PRIME_CONST = 31;
int hash_function(string key);
int hash_function(int key);
// std::hash?
void rehash();
public:
HashTable() {
cout << "ht cstructed, intitial_capacity is (default:) " << CAPACITY << endl;
}
HashTable(int initial_capacity) {
cout << "ht cstructed, intitial_capacity is " << initial_capacity << endl;
CAPACITY = initial_capacity;
}
//// RULE OF THREE
//// copy ctor
//HashTable(HashTable& const ht);
//// destructor
//~HashTable();
//// (copy) assignment operator
//HashTable& operator=(HashTable& const ht);
//// RULE OF FIVE
//// move ctor
//HashTable(HashTable&& ht); // && -> rvalue
//// move assignment operator
//HashTable& operator=(HashTable&& ht);
//// Hash Table operations
void put(Key key, Value value) {
// allocate memory with first put
if (current_total == 0)
table = new list<HashItem<key, value>>[CAPACITY];
HashItem<key, value>* hi = new HashItem(key, value);
int hash = hash_function(key);
if (find(table[hash].begin(), table[hash].end(), *hi) == table[hash].end()) {
// only put if not already in list
table[hash].push_back(*hi);
}
current_total++;
//cout << "current total is " << current_total << " of " << FILL_LEVEL * CAPACITY << endl;
// rehash check
if (current_total > (FILL_LEVEL * CAPACITY)) {
rehash();
//cout << "fill level reached: rehashed" << endl;
}
}
//void remove(int key, string value);
//string get(int key);
//// for part b)
//HashItem& get_item(int key) {
// int list_index = hash_function(key); // list_index = hash_code
// if (!table[list_index].empty()) {
// for (auto &list_item : table[list_index]) {
// if (key == list_item.key) {
// return list_item;
// }
// }
// }
// HashItem hi(key, "");
// return hi;
//}
//friend ostream& operator<<(ostream& os, const HashTable& ht);
//void clear();
//bool contains(int key);
//bool contains_value(string value);
//// fill levels
//void set_fill_level(float new_level);
//float get_fill_level();
//// b)
//// Overloading [] operator to access elements in array style
//HashItem& operator[] (int key) {
// if (this != nullptr)
// return this->get_item(key);
// HashItem hi(key, "");
// // stand-in hash item in case not in hash table
// return hi;
//}
};
Call in my main.cpp:
#include <iostream>
#include "HashTable.h"
using namespace std;
#define DEBUG(X) cout << (#X) << " = " << (X) << endl
HashTable<int, string> ht;
void put_test() {
cout << "--------------- put test ----------------------------------" << endl;
ht.put(10, "test");
}
int main() {
put_test();
}

Very strange errors while using cout in module file

Sorry, I couldn't make an MRE, the error doesn't happen in the cut code, but I will cut the code as much as possible.
main.cpp
#include <iostream>
#include "Functions.h"
using namespace std;
import TNode;
//USE C++20
int main()
{
string line;
cout << "Enter line:\n";
getline(cin, line);
TNode<char> head = stringToBinaryTree(line);
line;
}
Functions.h
#pragma once
#include <string>
using namespace std;
import TNode;
TNode<char> stringToBinaryTree(string s);
Functions.cpp
#include "Functions.h"
using namespace std;
TNode<char> stringToBinaryTree(string s) {
if (s.size() == 0) return TNode<char>();
TNode<char> result(s[0]);
for (size_t i = 1; i < s.length(); i++)
{
result.addChildren(s[i]);
}
return result;
}
TNode.ixx (cut)
module;
#include <iostream>
export module TNode;
export{
template <class T> class TNode;
}
using namespace std;
template <class T>
class TNode {
T value;
TNode<T>* leftChildren;
TNode<T>* rightChildren;
TNode<T>* Parent;
public:
TNode();
TNode(const T value);
TNode(TNode<T>& parent, const T value);
TNode(const TNode<T>& copyTree);
TNode<T>& operator=(const TNode<T>& source);
TNode<T>* addChildren(T value);
TNode<T>* left() const;
TNode<T>* right() const;
TNode<T>* parent() const;
T getValue() const;
void setValue(T value);
};
//then only the used methods and functions
template <class T> TNode<T>::TNode(TNode<T>& parentNode, const T value) {
this->value = value;
leftChildren = nullptr;
rightChildren = nullptr;
Parent = nullptr;
if (parentNode.getValue() >= value) {
if (parentNode.right() != nullptr) TNode(*parentNode.right(), value);
else {
parentNode.rightChildren = this;
Parent = &parentNode;
}
}
else {
if (parentNode.left() != nullptr) TNode(*parentNode.left(), value);
else {
parentNode.leftChildren = this;
Parent = &parentNode;
}
}
}
template <class T> TNode<T>* TNode<T>::addChildren(T value) {
TNode<T>* children = new TNode<T>(*this, value);
return children;
}
template <class T> void recursionCopy(TNode<T>* dest, const TNode<T>* source) {
dest->addChildren(source->getValue());
//cout << "Added " << source->getValue() << "to destination"; //if uncomment this happens error C2995 and C2572
//if (dest->parent()) cout << " with parrent " << dest->parent() << "\n"; //but if uncomment this while still have prev line uncommented its LNK2005 and LNK1169 errors now
//else cout << "\n";
if (source->left()) {
//cout << "Goind to left with value " << source->left()->getValue() << "\n";
recursionCopy(dest, source->left());
}
if (source->right()) {
//cout << "Goind to right with value " << source->right()->getValue() << "\n";
recursionCopy(dest, source->right());
}
}
template <class T> TNode<T>::TNode(const TNode<T>& copyTree) {
value = copyTree.value;
recursionCopy(this, &copyTree);
}
template <class T> T TNode<T>::getValue() const {
return value;
}
template <class T> TNode<T>* TNode<T>::parent() const {
return Parent;
}
The problem happens in the recursionCopy() function.
When I don't uncomment the cout code, there are no compilation or link errors.
When I uncomment the first line where I used getValue(), the compiler is getting MAD and saying the operator!= template is already defined. Why? I am not defining or using operator!=, but it gives me this error from the <iosfwd> file.
But the interesting part comes when I uncomment the second line with parent(), it causes linker errors with 8 functions, but in Functions.obj for some reason. Here one of the linker errors:
"public: void __thiscall std::basic_ostream<char,struct std::char_traits<char> >::_Osfx(void)" (?_Osfx#?$basic_ostream#DU?$char_traits#D#std###std##QAEXXZ)" already defined in Functions.obj

BST inorder method referencing vector showing error: declaration is incompatible

I am a beginner at c++ and I am coding a program that stores data into a BST template class the being another class called log_t that stores the variables, I am trying to use the inorder method from the BST class to reference a vector from main, to input the values into and be able to use it in the main class
my main class
int main(int argc, char* argv[])
{
BST<log_t> l;
string infilename = "";
string filePath = "data\\";
string files[1] = {
filePath + "MetData-31-3a.csv"
//filePath + "Jan20071toDec31abcdefghijklmnopq",
//filePath + "Jan20081toDec31abcdefghijklmnopq",
//filePath + "MetData_Jan01-2010-Jan01-2011-ALL"
};
/// checks if file can open
for (int i = 0; i < 1; i++) {
infilename = files[i];
ifstream infile(infilename);
if (!infile.is_open())
{
cout << "unable to read file" << files[i] << endl;
}
else
{
cout << "reading file" << files[i] << endl;
}
/* parse sensor data csv file */
string tmp;
getline(infile, tmp); // skip the first line
while (getline(infile, tmp))
{
// if successfully parsed then append into vector
log_t logline;
if (ParseLog(tmp, logline))
l.insert(logline);
}
}
cout << " end with reading file" << endl;
/* aggregate/filter logs */
Vector<log_t> vec;
l.inorder(vec);
/* prompt menu */
// this array stores all the menu option callback functions
void(*funs[])(const Vector<log_t> & vec) = { NULL, &option1, &option2, &option3, &option4, &option5,&option6 };
// keep printing menu in loop
while (true)
{
// prompt menu and ask user to select option
int choice = PromptMenu();
// check validity of choice
if (choice < 1 || choice > 6)
{
cout << "invalid choice" << endl;
}
else
{
cout << endl;
// call menu option handler
(funs[choice])(vec);
}
}
system("pause");
return -1;
}
my BST class
#include <string>
#include <iostream>
#include <stream>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "log_t.h"
#include "Vector.h"
using namespace std;
template <class T>
class BST {
private:
struct Node {
T num;
Node* left;
Node* right;
};
Node* root = NULL;
Node* insert(Node* node, T x);
Node* newnode(T num);
void removeprivate(T num, Node* parent);
T findsmallestprivate(Node* ptr);
void inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const& log);
void postorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
void preorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
//void inorderprivate(Node* ptr);
//void postorderprivate(Node* ptr);
//void preorderprivate(Node* ptr);
void removematch(Node* parent, Node* match, bool left);
public:
void insert(T num);
void remove(T num);
void removerootmatch();
T findsmallest();
void inorder(Vector<log_t>const& log);
void postorder();
void preorder();
void print(T& p) { cout << p << " "; };
};
template <class T>
void BST<T>::inorder(Vector<log_t>const& log) {
inorderprivate(root,print,log);
}
template <class T>
void BST<T>::inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const&
log) {
if (root != NULL)
{
if (ptr->left != NULL)
{
inorderprivate(ptr->left, FT);
}
(this->*FT)(log);
log.Append( ptr->num);
if (ptr->right != NULL)
{
inorderprivate(ptr->right, FT);
}
}
else
{
cout << "tree is empty";
}
}
my log_t class the T type
#pragma once
#ifndef LOG_T_H
#define LOG_T_H
#include <iostream>
#include <stream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "BST.h"
class log_t
{
public:
log_t();
log_t(log_t& log);
float gettemp();
float getwind();
float getsolar();
void setwind(float wind);
void setsolar(float rad);
void settemp(float temp);
Date date;
Times time;
private:
float wind_speed;
float solar_radiation;
float air_temperature;
};
log_t::log_t()
{
wind_speed = 0;
solar_radiation = 0;
air_temperature = 0;
}
log_t::log_t(log_t& log) {
wind_speed = log.wind_speed;
solar_radiation = log.solar_radiation;
air_temperature = log.air_temperature;
date.SetDate(log.date.GetDay(), log.date.GetMonth(), log.date.GetYear());
time.SetHour(log.time.GetHour());
time.SetMinute(log.time.GetMinute());
}
float log_t:: gettemp()
{
return air_temperature;
}
float log_t::getwind() {
return wind_speed;
}
float log_t::getsolar() {
return solar_radiation;
}
void log_t::setwind(float wind)
{
wind_speed = wind;
}
void log_t::setsolar(float rad)
{
solar_radiation = rad;
}
void log_t::settemp(float temp)
{
air_temperature = temp;
}
#endif // LOG_T_H
my vector class
#pragma once
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <stream>
#include <string>
template <class T>
class Vector
{
public:
Vector();
Vector(int capacity);
Vector(const Vector& vec);
Vector& operator=(const Vector& vec);
~Vector();
int GetSize() const;
void Expand();
T& GetLast();
void Append(const T& val);
T& operator[](int idx);
const T& operator[](int idx) const;
private:
T* elems;
int capacity;/** < int capacity, stores the size of the array */
int count;
void CopyFrom(const Vector& vec);
};
template <class T>
inline Vector<T>::Vector() : elems(nullptr), capacity(0), count(0)
{
}
template <class T>
inline Vector<T>::Vector(int capacity)
: elems(new T[capacity]()), capacity(capacity), count(0)
{
}
template <class T>
inline Vector<T>::Vector(const Vector& vec)
{
CopyFrom(vec);
}
template <class T>
inline Vector<T>& Vector<T>::operator=(const Vector& vec)
{
if (elems)
delete[] elems;
CopyFrom(vec);
return *this;
}
template <class T>
inline Vector<T>::~Vector()
{
if (elems)
delete[] elems;
}
template <class T>
inline int Vector<T>::GetSize() const
{
return count;
}
template <class T>
inline void Vector<T>::Expand()
{
++count;
if (count > capacity)
if (capacity)
capacity *= 2;
else
capacity = 4;
T* tmp = new T[capacity]();
for (int i = 0; i < count - 1; ++i)
tmp[i] = elems[I];
if (elems)
delete[] elems;
elems = tmp;
}
template <class T>
inline T& Vector<T>::GetLast()
{
return elems[count - 1];
}
template <class T>
inline void Vector<T>::Append(const T& oval)
{
Expand();
GetLast() = val;
}
template <class T>
inline T& Vector<T>::operator[](int idx)
{
return elems[idx];
}
template <class T>
inline const T& Vector<T>::operator[](int idx) const
{
return elems[idx];
}
template <class T>
inline void Vector<T>::CopyFrom(const Vector& vec)
{
elems = new T[vec.capacity]();
capacity = vec.capacity;
count = vec.count;
for (int i = 0; i < count; ++i)
elems[i] = vec.elems[i];
}
#endif //VECTOR_H
the errors that keep showing up are
Severity Code Description Project File Line Suppression State
Error (active) E0147 declaration is incompatible with "void BST::inorder(const Vector<> &log)" (declared at line 241 of "C:\Users\Frances\Documents\A2\A2\BST.h") A2 C:\Users\Frances\Documents\A2\A2\BST.h 241
Severity Code Description Project File Line Suppression State
Error C2065 'log_t': undeclared identifier A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
Severity Code Description Project File Line Suppression State
Error C2923 'Vector': 'log_t' is not a valid template type argument for parameter 'T' A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
could someone help me figure out what it is that's causing this or what I am doing wrong, I have been trying to find an answer for hours and haven't been successful thank you

Printing std::strings produces no output

I was building a small template stack class for a side project and it appeared to be working correctly. However, when I tried it with strings it doesn't appear to work. I have no compilation errors or warnings. I simply get no output. I'm a little rusty in C++ but I wasn't expecting to get blocked by a problem that seems this simple.
My main function (for testing):
#include <iostream>
#include <fstream>
#include <string>
#include "myStack.h"
int main()
{
bool repeat = true;
int option = -1;
std::cout << "Option (1 - String | 2 - Integer) : ";
std::cin >> option;
std::cout << "\n";
switch (option)
{
case 1:
{
myStack<std::string> stringStack;
stringStack.push("!");
stringStack.push("there");
stringStack.push("Hello");
stringStack.show();
break;
}
case 2:
{
myStack<int> intStack;
intStack.push(3);
intStack.push(2);
intStack.push(1);
intStack.show();
break;
}
default:
break;
}
std::cout << "\n";
return 0;
}
Relevant parts of my stack class:
#pragma once
template <typename T>
class myStack
{
private:
T *elements;
size_t capacity;
public:
myStack();
T top();
size_t size();
void push(T pushed);
void pop();
bool isEmpty();
void show(std::ostream &out = std::cout);
};
template <typename T>
myStack<T>::myStack()
{
this->elements = NULL;
this->capacity = 0;
}
template <typename T>
void myStack<T>::push(T pushed)
{
this->elements = (T *)realloc(this->elements, (this->capacity + 1) * sizeof(T));
this->elements[this->capacity] = pushed;
this->capacity++;
}
template<typename T>
void myStack<T>::show(std::ostream &out)
{
for (int i = this->capacity - 1; i >= 0; i--)
{
out << this->elements[i] << std::endl;
}
}
Use of
this->elements = (T *)realloc(this->elements, (this->capacity + 1) * sizeof(T));
this->elements[this->capacity] = pushed;
to manage an array of std::strings is not right. Use of realloc to allocate memory is ok. However, it does not initialize the object properly. The second line is cause for undefined behavior since the object was not initialized properly.
If you are allowed to use std::vector, use it.
template <typename T>
class myStack
{
private:
std::vector<T> elements;
...
};
Then, use of capacity can be replaced by elements.size().
push can be simplified to:
template <typename T>
void myStack<T>::push(T pushed)
{
this->elements.push_back(pushed);
}
You'll have to update show() accordingly too.

Debug Assertion Failed! C++ VS2012 - Template Class

I'm doing an assignment and I've put together a template class for a Vector, and now have inherited it (per the assignment) to make it a sort-able. At the very end of the void SearchableVector<T>::add(T itemToAdd) method it throws a Debug Assertion Failed! error. The full text of the error is as follows:
---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Assertion Failed!
Program: ...tudio 2012\Projects\COSC 1437\Program 10\Debug\Program 10.exe
File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
Line: 52
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
---------------------------
Abort Retry Ignore
---------------------------
I've looked around and I realize this is a pretty common error usually related to memory management. Often calling delete on inappropriate things. I must be doing something similar because I'm getting the error, but I cannot find what I'm doing wrong. If you could help me out and/or point me in the right direction that would be much appreciated.
Main.cpp
#include "SimpleVector.h"
#include "SearchableVector.h"
#include <stdlib.h>
#include <time.h>
void main()
{
srand (time(NULL));
SearchableVector<int> v(0);
for (int i = 0; i < 20; i++)
{
v.add(rand() % 20);
}
v.print();
}
SimpleVector.h
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <stdexcept>
#include <iomanip>
using namespace std;
template<class T>
class SimpleVector {
public:
//Constructors
SimpleVector(); //default constructor, size 0
SimpleVector(int); //parameterized constructor with default size
SimpleVector(const SimpleVector& a); //copy constructor
~SimpleVector(); //destructor
T& operator[](int) const;
SimpleVector<T>& operator=(SimpleVector<T>);
const bool operator==(SimpleVector&) const;
void push_back(T);
T& pop_back();
T& getElement(int);
int getSize() const;
void print() const;
protected:
int size;
T* internalArray;
void SimpleVector<T>::swap(SimpleVector&);
};
template<class T>
SimpleVector<T>::SimpleVector()
{
size = 0;
internalArray = nullptr;
}
template<class T>
SimpleVector<T>::SimpleVector(int sizeOfArray)
{
if (sizeOfArray < 0) throw "SimpleVector size must not be less than 0";
internalArray = new T[sizeOfArray]();
size = sizeOfArray;
}
template<class T>
SimpleVector<T>::SimpleVector(const SimpleVector& vectorToCopy):size(vectorToCopy.getSize()), internalArray( new T[vectorToCopy.getSize()] )
{
for (int i = 0; i < size; i++)
internalArray[i] = vectorToCopy.internalArray[i];
}
template<class T>
SimpleVector<T>::~SimpleVector() {
//cout << "Destructor called" << std::endl;
delete[] internalArray;
}
template<class T>
T& SimpleVector<T>::operator[](int i) const {
if (i<0 || i>=size) throw "Vector::operator[] : index is out of range";
return internalArray[i];
}
template<class T>
SimpleVector<T>& SimpleVector<T>::operator=(SimpleVector<T> rightSide) {
rightSide.swap(*this);
return *this;
}
template<class T>
const bool SimpleVector<T>::operator==(SimpleVector& right) const {
if (size() != right.size())
return false;
else {
for (int i = 0; i < size(); i++){
if (internalArray[i] != right[i])
return false;
}
}
return true;
}
template<class T>
void SimpleVector<T>::push_back(T itemToAdd) {
SimpleVector<T> temp(size + 1);
for (int i = 0; i < size; i++)
temp[i] = internalArray[i];
temp[size] = itemToAdd;
temp.swap(*this);
}
template<class T>
T& SimpleVector<T>::pop_back()
{
SimpleVector<T> temp(size - 1);
for (int i = 0; i < size; i++)
temp[i] = internalArray[i];
T pop = internalArray[size-a];
temp.swap(*this);
return pop;
}
template<class T>
T& SimpleVector<T>::getElement(int indexToGet)
{
return internalArray[indexToGet];
}
template<class T>
int SimpleVector<T>::getSize() const {
return this->size;
}
template<class T>
void SimpleVector<T>::print() const
{
for (int i = 0; i < size; i++)
{
std::cout << internalArray[i];
if (i!=(size-1))
std::cout << ",";
else
std::cout << std::endl;
if (i%10 == 0 && i!=0)
std::cout <<std::endl;
}
}
template<class T>
void SimpleVector<T>::swap(SimpleVector& other)
{
std::swap(internalArray, other.internalArray);
std::swap(size, other.size);
}
#endif
SearchableVector.h
#ifndef SEARCHABLEVECTOR_H
#define SEARCHABLEVECTOR_H
#include "SimpleVector.h"
template<class T>
class SearchableVector : protected SimpleVector<T>
{
public:
SearchableVector(int);
SearchableVector(const SearchableVector&);
~SearchableVector();
void add(T);
T getElement(int);
int getSize() const;
void print() const;
int search(T);
};
template<class T>
SearchableVector<T>::SearchableVector(int sizeOfArray) : SimpleVector(sizeOfArray)
{
}
template<class T>
SearchableVector<T>::SearchableVector(const SearchableVector& vectorToCopy) : SimpleVector(vectorToCopy)
{
}
template<class T>
SearchableVector<T>::~SearchableVector()
{
delete[] internalArray;
}
template<class T>
void SearchableVector<T>::add(T itemToAdd)
{
bool flag = false;
SearchableVector<T> temp(size + 1);
for (int i = 0; i < size; i++)
{
if ((itemToAdd <= internalArray[i]) && (flag == false))
{
temp[i] = itemToAdd;
i++;
flag = true;
}
temp[i] = internalArray[i];
}
if (flag == false)
temp[size] = itemToAdd;
temp.swap(*this);
} // !*******************! THROWS THE ERROR RIGHT HERE !*******************!
template<class T>
T SearchableVector<T>::getElement(int elementToGet)
{
return SimpleVector::getElement(elementToGet);
}
template<class T>
int SearchableVector<T>::getSize() const
{
return SimpleVector::getSize();
}
template<class T>
void SearchableVector<T>::print() const
{
SimpleVector::print();
}
template<class T>
int SearchableVector<T>::search(T itemToSearchFor)
{
}
#endif
First of all, when using inheritance, 99% of the time you should use a virtual destructor.
That's very important.
virtual ~SimpleVector();
When deleting an object, its base class destructor is called too.
And in your case you have delete[] internalArray; in both destructors.
Just leave that delete in the base class, because that member belongs to it, and it should take care of it.
Next time you encounter something like this, put a breakpoint near all the delete calls for that object type, then you can see which ones are called and in what order.