Stack Data Structure Parenthesis Matching - c++

I was trying this parenthesis matching stack code and every time I run this it only gives me that parenthesis are not matching I don't know what is going wrong. Can you guys please help me out in this and tell me how can I improve this further and is this the right way to use stack in c++ because I was studying from a source that is using c language.
#include<iostream>
using namespace std;
struct stack
{
int size;
int top;
char *arr;
};
int isEmpty(struct stack *ptr)
{
if(ptr->top==-1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size-1)
{
return 1;
}
return 0;
}
void push(struct stack *ptr,char val)
{
if(isFull(ptr))
{
cout<<"stack overflow"<<endl;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
cout<<"stack underflow"<<endl;
return -1;
}
else
{
char val = ptr->arr[ptr->top];
ptr->top-1;
return val;
}
}
int parenthesisMatch (char * exp)
{
struct stack * sp = new struct stack;
sp->size = 80;
sp->top = -1;
sp->arr = new char(sp->size);
for(int i=0; exp[i]!='\0'; i++)
{
if (exp[i] == '(')
{
push(sp,'(');
}
else if(exp[i] == ')')
{
if (isEmpty(sp))
{
return 0;
}
pop(sp);
}
}
if (isEmpty(sp))
{
return 1;
}
return 0;
}
int main()
{
char *exp = "((8)(*--$$9))";
if(parenthesisMatch(exp))
{
cout<<"The parenthesis is matching\n";
}
else
{
cout<<"The parenthesis is not matching\n";
}
return 0;
}

Just tried to debug the code and found 2 potential errors:
As correctly pointed out by #Welbog in the comments, to create an array, use sp->arr = new char[sp->size; in the function parenthesisMatch().
In the function pop(), the value of the top is not decremented correctly.
Have a look at the working code:
#include<iostream>
struct stack
{
int size;
int top;
char *arr;
};
int isEmpty(struct stack *ptr)
{
if(ptr->top==-1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size-1)
{
return 1;
}
return 0;
}
void push(struct stack *ptr,char val)
{
if(isFull(ptr))
{
std::cout<<"stack overflow"<<std::endl;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
std::cout<<"stack underflow"<<std::endl;
return -1;
}
else
{
char val = ptr->arr[ptr->top];
ptr->top-=1;
return val;
}
}
int parenthesisMatch (char * exp)
{
struct stack * sp = new struct stack;
sp->size = 80;
sp->top = -1;
sp->arr = new char[sp->size];
for(int i=0; exp[i]!='\0'; i++)
{
if (exp[i] == '(')
{
push(sp,'(');
}
else if(exp[i] == ')')
{
if (isEmpty(sp))
{
return 0;
}
pop(sp);
}
}
if (isEmpty(sp))
{
return 1;
}
return 0;
}
int main()
{
char *exp = "((8)(*--$$9))";
if(parenthesisMatch(exp))
{
std::cout<<"The parenthesis is matching\n";
}
else
{
std::cout<<"The parenthesis is not matching\n";
}
return 0;
}

Related

Error when declaring more than one object from the same class "polynomial"

In this code, it runs fine when I have declared only one object of polynomial class. But as soon as I declare two objects of polynomial class, it does not show any error, but the code does not run. Not even the first line of int main().
I have checked all other functions individually. The only problem is declaration of more than one polynomial class objects!!!
#include<iostream>
#include<fstream>
#include<string>
#include<cstring>
#include<math.h>
using namespace std;
string space_rem(string s)
{
int i;
string res;
for(i=0;i<s.size();i++)
{
if(s[i] != ' ')
res+=s[i];
}
return res;
}
string all_in_powers(string s) //writes every variable in string in its power form x^(i)
{ //e.g. abca is written as a^(1)b^(1)c^(1)a^(1)
string temp = s;
if(temp.size()==0)
return temp;
int i;
if(temp[temp.size()-1]>='a'&&temp[temp.size()-1]<='z')
temp+="^(1)";
string res;
char x;
for(i=0;i<temp.size()-3;i++)
{
x=temp[i];
if(x>='a' && x<='z' && temp[i+1]!='^') //if variable not in power form
{
res+=x;
res+="^(1)"; //writes ab as a^(1)b^(1)
}
else
{
res+=x; //variable in power form so copy as it is
}
}
for(i=temp.size()-3;i<temp.size();i++)
{
res+=temp[i];
}
return res;
}
class polynomial_term //stores everything regarding a polynomial term
{
public:
int powers[26]={0}; //power of each variable from a to z
string pol; //string representation of term without coefficient
int coeff; //coefficient of term
char sign;
int pow_sum; //positive or negative
public:
void full_term(string s); //inputs string form and puts all the data of the term in this class's object
void string_construct(); //makes the string representation pol from the powers array
void pol_pow(string s); //gathers data of total power of each variable from input string
void display(); //displays the complete polynomial term
polynomial_term operator * (polynomial_term); //to multiply two terms
bool operator < (polynomial_term);
bool operator > (polynomial_term);
bool operator == (polynomial_term);
void display_pow();
polynomial_term operator + (polynomial_term);
void copy_frm(polynomial_term);
};
void polynomial_term::copy_frm(polynomial_term B)
{
for(int i=0;i<26;i++)
{
powers[i]=B.powers[i];
}
coeff=B.coeff;
pol=B.pol;
sign=B.sign;
pow_sum=B.pow_sum;
}
void polynomial_term:: display_pow()
{
for(int i=0;i<26;i++)
{
cout<<powers[i]<<" ";
}
cout<<endl;
}
void polynomial_term::display()
{
/*if(coeff==0)
{
cout<<"0\n";
}*/
if(coeff==1)
{
if(pol.size()!=0)
cout<<pol<<endl;
else
{
cout<<1<<endl; //only coefficient printed as pol is empty
}
}
else
{
if(coeff!=-1)
cout<<coeff<<pol<<endl;
else
cout<<"-"<<pol<<endl;
}
}
void polynomial_term::string_construct() //generates pol member of polynomial term class using powers array
{
pol.clear();
/*if(coeff!=1)
{
pol+=to_string(coeff);
}*/
for(int i=0;i<26;i++)
{
if(powers[i]!=0)
{
pol+=(char)(i+'a');
if(powers[i]!=1)
{
pol+="^(";
pol+=to_string((powers[i]));
pol+=')';
}
}
}
}
void polynomial_term::pol_pow(string s) //
{
char x;
if(s.size()==0)
return;
for(int i=0;i<s.length();i++)
{
x=s[i];
if(x>='a'&&x<='z')
{
string tmp;
int pow;
for(int j=i+3;s[j]!=')';j++) //gathers power of variable in tmp string
{
tmp+=s[j];
}
pow=stoi(tmp);
powers[x-'a']+=pow;
}
}
pow_sum=0;
for(int i=0;i<26;i++)
{
pow_sum+=powers[i];
}
}
void polynomial_term::full_term(string s) //inputs raw string and organises its data in the polynomial_term class object
{
sign='+'; //default sign
coeff=1; //default coefficient
for(int i=0;i<26;i++)
{
powers[i]=0;
}
pol.clear();
pow_sum=0;
int i=0;
if(s[0]=='-')
{
sign='-';
i++;
}
string tmp;
while(i<s.size() && s[i]>='0' && s[i]<='9') //tmp collects the coefficient part
{
tmp+=s[i];
i++;
}
if(tmp.size()>0)coeff=stoi(tmp);
if(sign=='-')
coeff*=-1;
tmp="";
if(1)
{
for(int j=i;j<s.length();j++)
{
tmp+=s[j];
}
}
s=tmp;
s=all_in_powers(s);
pol_pow(s);
string_construct();
}
polynomial_term polynomial_term::operator * (polynomial_term B) //returns multiplication of terms
{
polynomial_term res;
res.coeff=coeff*B.coeff;
if(res.coeff<0)
res.sign='-';
string temp=pol+B.pol;
temp=all_in_powers(temp);
res.pol_pow(temp);
res.string_construct();
return res;
}
bool polynomial_term::operator < (polynomial_term B) //lexicographic order comparison
{
// bool flag=0;
/*if(pow_sum==B.pow_sum)
{
for(int i=0; i<26; i++)
{
if(powers[i]>B.powers[i])
{
//if(B.powers[i]==0)
//return false;
return false;
}
else if(powers[i]<B.powers[i])
{
return true;
}
}
}*/
for(int i=0; i<26; i++)
{
if(powers[i]>B.powers[i])
{
//if(B.powers[i]==0)
//return false;
return true;
}
else if(powers[i]<B.powers[i])
{
return false;
}
}
return false;
}
bool polynomial_term::operator > (polynomial_term B) //lexicographic order comparison
{
for(int i=0; i<26; i++)
{
if(powers[i]>B.powers[i])
return false;
else
{
if(powers[i]<B.powers[i])
return true;
else
continue;
}
}
return false;
}
bool polynomial_term::operator == (polynomial_term B)
{
for(int i=0;i<26;i++)
{
if(powers[i] != B.powers[i])
return false;
}
return true;
}
polynomial_term polynomial_term::operator + (polynomial_term B) //return addition of polynomial_terms
{
polynomial_term C;
if(pol!=B.pol)
{
cout<<"Error: Adding two non_compatible polynomial terms!!\n";
}
C.coeff = coeff+B.coeff;
if(C.coeff<0)
C.sign='-';
else
C.sign='+';
C.pol=pol;
//cout<<"*\n";
C.pol_pow(all_in_powers(pol));
//cout<<"**\n";
C.string_construct();
//cout<<"*\n";
return C;
}
class polynomial
{
public:
polynomial_term terms[10000];
int term_count;
string expression;
public:
void expression_generate();
polynomial(): term_count(0),expression("0")
{
polynomial_term X;
X.full_term("0");
for(int i=0;i<10000;i++)
{
terms[i].copy_frm(X);
}
}
polynomial(string s) //constructor segregates terms and stores them in terms array
{
//cout<<"uo\n";
polynomial_term X;
X.full_term("0");
for(int i=0;i<10000;i++)
{
terms[i].copy_frm(X);
}
s=all_in_powers(s);
polynomial_term tmp;
string temp="";
int i;
for(i=0;!(i!=0 && s[i]=='+'|| s[i]=='-') && i<s.size();i++) //put first term in the array
{
temp+=s[i];
}
cout<<"***"<<i<<endl;
tmp.full_term(temp);
terms[0]=tmp;
temp="";
term_count=1;
while(i<s.size())
{
if(s[i]=='+' )
{
temp="";
i++;
while(s[i]!='+' && s[i]!='-' && i<s.size())
{
temp+=s[i];
i++;
}
tmp.full_term(temp);
terms[term_count]=tmp;
term_count++;
}
else if(s[i]=='-')
{
temp="-";
i++;
while(s[i]!='+' && s[i]!='-' && i<s.size())
{
temp+=s[i];
i++;
}
tmp.full_term(temp);
terms[term_count]=tmp;
term_count++;
}
}
expression_generate();
}
void lexicosort();
void powersort();
void display_terms();
//void expression_generate();
void display();
bool found(polynomial_term);
};
void polynomial::display_terms()
{
for(int i =0;i<term_count;i++)
{
terms[i].display();
}
}
void polynomial::display()
{
cout<<expression<<endl;
}
void polynomial::powersort()
{
polynomial_term least;
int least_index,i,j;
for(i=0;i<term_count;i++)
{
least = terms[i];
least_index = i;
for(j=i;j<term_count;j++)
{
if(terms[j].pow_sum<least.pow_sum)
{
least=terms[j];
least_index=j;
}
}
polynomial_term temp = terms[i];
terms[i] = terms[least_index];
terms[least_index] = temp;
}
}
void polynomial::lexicosort()
{
polynomial_term least;
int least_index,i,j;
for(i=0;i<term_count;i++)
{
least = terms[i];
least_index = i;
for(j=i;j<term_count;j++)
{
if(terms[j]<least)
{
least=terms[j];
least_index=j;
}
}
polynomial_term temp = terms[i];
terms[i] = terms[least_index];
terms[least_index] = temp;
}
}
void polynomial::expression_generate()
{
// cout<<"**\n";
expression.clear();
expression="";
if(term_count==0)
{
//cout<<"*\n";
expression="0";
return;
}
for(int i=0;i<term_count;i++)
{
//cout<<"lolo\n";
if(terms[i].coeff==0)
{
if(i==1)
{
expression="0";
return;
}
else
{
continue;
}
}
if((terms[i].coeff)!=1 && (terms[i].coeff)!=-1)
{
if(i!=0)
expression += terms[i].sign;
expression += to_string(terms[i].coeff);
}
else
{
if(i!=0)
expression += terms[i].sign;
}
expression += terms[i].pol;
}
}
bool polynomial::found(polynomial_term X)
{
for(int i=0;i<term_count;i++)
{
if(X==terms[i])
return true;
}
return false;
}
/*polynomial comp(polynomial A) //compresses by grouping similar terms (terms that can be added)
{
A.lexicosort();
A.expression_generate();
A.powersort();
A.expression_generate();
polynomial_term tmp;
tmp.copy_frm(A.terms[0]);
polynomial res;
for(int i=1;i<A.term_count;i++)
{
if(!(A.terms[i]==tmp))
{
res.terms[res.term_count].copy_frm(tmp);
res.term_count++;
tmp.copy_frm(A.terms[i]);
}
else
{
polynomial_term X=tmp+A.terms[i];
tmp.copy_frm(X);
}
}
res.expression_generate();
return res;
}*/
int main()
{
cout<<"*\n";
polynomial A("a");
// polynomial B;
cout<<"*\n";
polynomial B("a+b+b+a");
A.display();
cout<<"*\n";
/* A.lexicosort();
A.expression_generate();
A.powersort();
A.expression_generate();
cout<<"*\n";
A.display_terms();
cout<<"*\n";*/
//res.expression_generate();
//res.display();
}

When inheriting from a class, do the variables inherited get redefined by the inherited class through the parent class?

I have made two classes: stack1 and stack2 and defined my own stack operations of push(), pop(), isempty() and isfull(). I am trying to calculate a postfix expression from an input. I have made another class called operation that is a child of stack1 and stack2, so I can access the functions of push(),pop(), etc.. within operation. I have a function within operation called operate() that does the dirty work on the stacks. Within this function I have a while loop that depends on stack1 not being empty until the operation is complete; HOWEVER, when I step through this function top1, where stack1 is pointing to, has been reset to 0. Is there a way to overcome this/am I doing something wrong? This is the first time I am using classes and such, so I am not sure of the ins and outs.
Here are the definitions of my classes:
class stack1 {
private:
int num1[SIZE/2]; int top1;
public:
void push1(int data)
{
if (is_full1());
else
{
num1[top1] = data;
top1++;
}
}
int pop1(void)
{
if(is_empty1());
else
{
top1--;
return num1[top1];
}
}
int is_empty1(void)
{
if(top1 == 0)
{
return 1;
}else
{
return 0;
}
}
int is_full1(void)
{
if(top1 == SIZE)
{
return 1;
}else
{
return 0;
}
}
stack1()
{
top1 = 0; num1[SIZE/2] = {0};
} };
class stack2 {
private:
int num2[SIZE/2]; int top2; public:
void push2(int data)
{
if (is_full2());
else
{
num2[top2] = data;
top2++;
}
}
int pop2(void)
{
if(is_empty2());
else
{
top2--;
return num2[top2];
}
}
int is_empty2(void)
{
if(top2 == 0)
{
return 1;
}else
{
return 0;
}
}
int is_full2(void)
{
if(top2 == SIZE)
{
return 1;
}else
{
return 0;
}
}
stack2()
{
top2 = 0; num2[SIZE/2] = {0};
} };
class operation: public stack2, public stack1 {
private:
int answer;
int a;
int b;
int num_cnt;
int ans;
int from_st1;
int from_st2;
public:
int c;
int oper(void)
{
answer = 0;
a = 0;
b = 0;
num_cnt = 0;
ans = 0;
c = 0;
stack1 st1;
stack2 st2;
while(!st1.is_empty1())
{
from_st1 = st1.pop1();
if(from_st1 == plus)
{
st2.push2(from_st1);
}else if(from_st1 == minus)
{
st2.push2(from_st1);
}else if(from_st1 == mult)
{
st2.push2(from_st1);
}else if (from_st1 == divide)
{
st2.push2(from_st1);
}else if(num_cnt == 1)
{
num_cnt = 0;
if(ans == 0)
{
answer = b;
ans++;
}
a = from_st1;
from_st2 = st2.pop2();
if(from_st2 == plus)
{
c = a+answer;
}else if(from_st2 == minus)
{
c = a-answer;
}else if(from_st2 == mult)
{
c = a*answer;
}else if(from_st2 == divide)
{
c = a/answer;
}
}else
{
b = from_st1;
}
num_cnt++;
}
return c;
}
operation()
{
answer = 0;
a = 0;
b = 0;
num_cnt = 0;
ans = 0;
from_st1 = 0;
from_st2 = 0;
} };
I think that the "problem" is with the line:
stack1 st1;
stack2 st2;
This will call the default constructor and set the value of the variables top1 and top2 as zero.
A workaround to this would be to initialise these variables with some positive non-zero value.
Hence the code would look something like(focusing only on the changed parts):
class stack1 {
private:
int num1[SIZE/2]; int top1;
public:
.....
stack1()
{
top1 = 0; num1[SIZE/2] = {0};
}
stack1(int top1)
{this.top1 = top1;}
};
class stack2 {
private:
int num2[SIZE/2]; int top2; public:
public:
.....
stack2()
{
top2 = 0; num2[SIZE/2] = {0};
}
stack2(int top2)
{this.top2 = top2;}
};
class operation: public stack2, public stack1 {
.....
public:
int c;
int oper(void)
{
.....
//just an example, can be declared explicitly as well
stack1 st1(5);
stack2 st2(7);
.....
Also, I would advice you to make your code a bit more readable(for instance the presence of 3-liner {} in if cases spanning only a single line). It is just unnecessary consumption of space.
And finally, if the "redefinition" of parent class' variables means the variables re-asserting some value on being inherited, they don't, unless you specify explicitly(such as using a constructor in our case to assign different values to top1 and top2). The inherited class will get a copy of the state of the parent class*.
*meaning they cannot be changed directly by the inherited class. For example if you would've done: int top1=5; initially then top1 would've been 5 until it were to be redefined again somewhere(such as using a constructor)
I take from the problem statement you are trying to build a basic calculator with four operators and need basic expression evaluation done using stack.
Say you have an expression: a+b-cd/e
looks like this in stack: TOP e->/->d->->c->-->b->+->a EMPTY
And this track needs to be evaluated.
Based on these.. you may be looking for something like below:
class stack {
private:
int num[SIZE];
int top;
public:
void push(int data)
{
if (is_full1());
else
{
num[top] = data;
top++;
}
}
int pop(void)
{
if(is_empty());
else
{
top--;
return num[top];
}
}
int is_empty(void)
{
if(top == 0)
{
return 1;
}else
{
return 0;
}
}
int is_full(void)
{
if(top == SIZE)
{
return 1;
}else
{
return 0;
}
}
stack()
{
top = 0; num[SIZE] = {0};
}
};
class operation {
private:
int answer;
int op1;
int op;
boolean isOperator(int val) {
boolen retVal = false;;
if (val == plus ||
val == minus ||
val == divide ||
val == mult) {
retVal = true;
}
else {
retVal = false;
}
return retVal;
}
public:
int oper(stack st1)
{
int from_st1 = 0;
while(!st1.is_empty())
{
from_st1 = st1.pop();
if(isOperator(from_st1))
{
op = from_st1;
}
else if(answer != 0)
{
op1 = from_st1;
if(op == plus)
{
answer = op1 + answer;
}else if(op == minus)
{
answer = op1 - answer;
}else if(op == mult)
{
answer = op1 * answer;
}else if(op == divide)
{
answer = op1 / answer;
}
}
else
{
answer = from_st1;
}
}
return answer;
}
operation()
{
answer = 0;
op1 = 0;
op = 0;
}
};
Note: You can do all evaluation with one stack don't need two stacks. Your operands can not equal to integer values for +, -, * and / for this assignment. You have a valid expression input into stack in main() code.

Class MinStack not giving output

Dynamically Initialization of MinStack is not able to do. Why?
#include<bits/stdc++.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
class Stack
{
int top;
int length;
int *arr;
public:
//Maximum size of Stack
Stack(int len)
{
top = -1;
length=len;
arr=new int[length];
} //constructor
void push(int data);
int pop();
bool isEmpty();
bool isStackFull();
int Size();
void Display();
int getPeek();
};
void Stack::push(int data)
{
if (isStackFull())
{
cout << "Stack Overflow"<<endl;
}
else
{
arr[++top] = data;
}
}
int Stack::pop()
{
if (isEmpty())
{
cout << "Stack Underflow"<<endl;
return 0;
}
else
{
int data = arr[top--];
return data;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
bool Stack::isStackFull()
{
return (top == length-1);
}
int Stack::Size()
{
return (top +1);
}
int Stack::getPeek()
{
return arr[top];
}
void Stack::Display()
{
for(int i=top;i!=-1;i--)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
class SpecialStack: public Stack
{
public:
Stack min1;
SpecialStack(int len):Stack(len)
{
min1= new Stack(len);
}
int pop();
void push(int x);
int getMin();
};
void SpecialStack::push(int x)
{
if(isEmpty()==true)
{
Stack::push(x);
min1.push(x);
}
else
{
Stack::push(x);
int y = min1.pop();
min1.push(y);
if( x < y )
min1.push(x);
else
min1.push(y);
}
}
/* SpecialStack's member method to remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
int x = Stack::pop();
min1.pop();
return x;
}
int SpecialStack::getMin()
{
int x = min1.pop();
min1.push(x);
return x;
}
int main()
{
SpecialStack s(3); //size of stack should be 3
s.push(10);
s.push(20);
s.push(30);
cout<<s.getMin()<<endl;
s.push(5);
cout<<s.getMin();
return 0;
}
Dynamically Initialization of MinStack is not able to do. Why, How to rectify this problem.Please explain.
In the SpecialStack constructor you initialize the base Stack properly, but not the min1 member. They should be handled the same way:
SpecialStack(int len):Stack(len),min1(len)
{ }
When you don't have min1 in the constructors initializer list, the compiler tries do call its default constructor, but the Stack class doesn't have one.

Using object of class as an parametr in method

I have method of class Stack, which compares 2 objects of this class:
bool comparison(T &stack) {
if (size == stack.size)
for (int i = 0; i < size; i++) {
if (!this->stackPr[i].comparison(stack.stackPr[i]))
return false;
}
else
return false;
return true;
}
and uses the method of class Time:
bool comparison(Time &time) {
if ((this->hours == time.hours) && (this->minutes == time.minutes) && (this->seconds == time.seconds))
return true;
return false;
When I try to use this comman in main:
bool temp = stack3.comparison(stack4);
MVS underlines |stack4| and shows me the error:
a reference of type "Time &"(non-const qualified) cannot be initialized with a value of type Stack<Time>
How could I handle this problem?
Thanks for your answers :)
There is class Stack:
class Stack {
private:
T *stackPr;
int size;
int top;
public:
//----------------CONSTRUCTORS-----------------
Stack(int n) {
if (n > 0)
size = n;
else
size = 10;
stackPr = new T[size];
top = -1;
}
Stack() {
size = 10;
stackPr = new T[size];
top = -1;
}
Stack(Stack &stack) {
stackPr = new T[stack.size];
size = stack.size;
top = stack.top;
for (int i = 0; i < size; i++)
stackPr[i] = stack.stackPr[i];
}
Stack(T *objs, int sizeMass) {
size = sizeMass;
stackPr = new T[size];
for (int i = 0; i < sizeMass; i++) {
this->push(objs[i]);
}
}
//----------------DESTRUCTOR-------------------
~Stack() {
delete[] stackPr;
}
//-----------------METHODS---------------------
//Add element to stack
void push(T &element) {
if (top == size - 1)
cout << "\nThere's no more place!!!\n";
else {
top++;
stackPr[top] = element;
cout << "\nElement was succesfully pushed\n";
}
}
//Read + Delete
T pop() {
if (top == -1)
cout << "\nStack is empty\n";
else {
T temp = stackPr[top];
stackPr[top] = 0;
top--;
cout << "\nElement was succesfully poped and deleted\n";
return temp;
}
}
//Read
T popup() {
if (top == -1)
cout << "\nStack is empty\n";
else {
cout << "\nElement was succesfully popped\n";
return stackPr[top];
}
}
//Comparison of 2 stacks
bool comparison(T &stack) {
if (size == stack.size)
for (int i = 0; i < size; i++) {
if (!this->stackPr[i].comparison(stack.stackPr[i]))
return false;
}
else
return false;
return true;
}
};
Try this, in your Stack class
change:
bool comparison(T &stack) {
for this:
bool comparison(Stack<T> &stack) {
First of all, abandon this comparison function, it hinders your code, use == instead.
Secondly, use const Stack<T> in your comparison function.
And finally, use auto to deduce the type of the variables.
Here is an example that shows the basics of what I just wrote:
#include <iostream>
using namespace std;
struct Time
{
bool operator==(const Time& time)
{
return true;// adjust it with your own needs.
}
};
template<typename T>
struct Stack
{
T val;
Stack(T& val_): val(val_) {}
bool operator==(const Stack<T>& stack)
{
return this->val == stack.val; // here is your business logic of comparison
}
};
int main()
{
Time t1;
Time t2;
Stack<Time> myStack1(t1);
Stack<Time> myStack2(t2);
auto temp = myStack1 == myStack2;
cout << temp << endl;
return 0;
}

C++ Double free or corruption Error when I believe I'm only freeing once

I'm having an issue with the last function in my code that destroys the array, I keep getting Double free or corruption which I think means I'm freeing it up twice but I can't figure out how i'm doing that
Main Code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
int main()
{
int_array arraytest;
init(arraytest);
if(arraytest.count==0)
{
cout<<"Empty array created"<<endl;
}
else
{
cout<<"Error in array creation"<<endl;
}
clear(arraytest);
if(arraytest.count==0)
{
cout<<"Array cleared of data"<<endl;
}
else
{
cout<<"Error in clear function"<<endl;
}
for(unsigned int i=0;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
for(unsigned int i=1;i<25;i+=2)
{
if(arraytest.count < arraytest.DEFAULT_CAPACITY)
{
add(arraytest,i);
print(arraytest);
}
else
{
add(arraytest,i);
print(arraytest);
}
}
if(arraytest.capacity == 2*arraytest.DEFAULT_CAPACITY)
{
cout<<"Resize function works properly"<<endl;
}
else
{
cout<<"Resize not working properly"<<endl;
}
if(contains(arraytest,6))
{
cout<<"Number 6 present in Array"<<endl;
}
else
{
cout<<"Number 6 not in Array Contains not working properly"<<endl;
}
if(contains(arraytest,30))
{
cout<<"Number 30 present in Array Contains not working properly"<<endl;
}
else
{
cout<<"Number 30 not in Array"<<endl;
}
if(remove(arraytest,23) && arraytest.count == 24)
{
cout<<"Number 23 removed from Array"<<endl;
}
else
{
cout << arraytest.count << endl;
cout<<"Number 23 not in Array error in remove"<<endl;
}
if(remove(arraytest,24) && arraytest.count == 23)
{
cout<<"Number 24 removed from Array"<<endl;
}
else
{
cout<<"Number 24 not in Array error in remove"<<endl;
}
if(remove(arraytest,0) && arraytest.count == 22)
{
cout<<"Number 0 removed from Array"<<endl;
}
else
{
cout<<"Number 0 not in Array error in remove"<<endl;
}
if(remove(arraytest,35))
{
cout<<"Error in remove function"<<endl;
}
else
{
cout<<"Number not in Array"<<endl;
}
destr(arraytest);
if(*arraytest.data == 0)
{
cout<<"Array destroyed"<<endl;
}
else
{
cout<<"Error in destroy"<<endl;
}
return 0;
}
Function code
#include "terrible_dynamic_size_array_unsorted.h"
using namespace std;
void init(int_array& arr)
{
arr.count = 0; //set count to 0
arr.capacity = arr.DEFAULT_CAPACITY;
arr.data = new int[arr.capacity];
}
void clear(int_array& arr)
{
destr(arr); //destroys array
init(arr); // initializes array
}
void destr(int_array& arr) //function for destroying array
{
delete[] arr.data;
//*arr.data = 0;
arr.count = 0;
}
void print(const int_array& arr) //prints out the array
{
for (unsigned int i = 0; i < arr.count; ++i)
cout << arr.data[i] << " ";
cout << endl;
}
bool contains(const int_array& arr, const int& target) //
{
unsigned int i;
for (i = 0; i < arr.count; ++i)
{
if (arr.data[i] == target) return true;
//else return false;
}
return false;
}
void resize(int_array& arr) //resizes the array --- WORKING
{
arr.capacity *= 2;
int* new_data = new int[arr.capacity];
for (unsigned int i = 0; i < arr.count; ++i)
{
new_data[i] = arr.data[i];
}
arr.data = new_data;
delete [] arr.data;
}
void add(int_array& arr, const int& payload)
{
if ((arr.count == arr.capacity))
resize(arr);
arr.data[++arr.count] = payload;
}
bool remove(int_array& arr, const int& target)
{
unsigned int i = 0;
if (arr.count == 0)
{
return false;
}
while (i <= arr.count && arr.data[i] != target) {i++;}
if (i > arr.count)
{
return false;
}
arr.data[i] = arr.data[arr.count];
arr.count--;
return true;
}
Header file
#include <iostream>
struct int_array {
int* data;
unsigned int count;
unsigned int capacity;
static const unsigned int DEFAULT_CAPACITY = 20;
};
void init(int_array& arr);
void destr(int_array& arr);
void resize(int_array& arr);
void clear(int_array& arr);
void add(int_array& arr, const int& payload);
bool contains(const int_array& arr, const int& target);
bool remove(int_array& arr, const int& target);
void print(const int_array& arr);
The problem lies with the function void destr(int_array& arr)
Thank you.
arr.data = new_data;
delete [] arr.data;
should be
delete[] arr.data;
arr.data = new_data;
Or, the old array will be leaked and arr.data will point to already freed memory - which will then be illegally freed again by destr.