I am trying to use a custom stack class to calculate an equation in postfix form. For some reason, the program keeps crashing.
Here is the stack header file
#ifndef aStack_h
#define aStack_h
#include <string>
#include <iostream>
using std::string; using std::cout;
class aStack
{
private:
int top, size;
int *stack;
public:
aStack(int s)
{
size = s;
top = -1;
stack = new int [s];
}
~aStack()
{
delete [] stack;
}
void reset();
void push(int);
void pop();
int getTop();
void getSize()
{
std::cout << size;
}
};
#endif
The class implementation file:
#include "aStack.h"
#include <iostream>
using namespace std;
void aStack::pop()
{
if (top == -1)
{ cout << "Stack is already empty.\n";}
stack[--top];
}
void aStack::push(int v)
{
if (top == size)
{ cout << "Stack is full.\n";}
stack[top++] = v;
}
void aStack::reset()
{
top = -1;
}
int aStack::getTop()
{
return top;
}
Here is the main program
#include <iostream>
#include "aStack.h"
#include <string>
using namespace std;
int main()
{
string equation {"35+1*"};
int op, count = 0, *oparray, result;
aStack stack(equation.length());
for (int i = 0; i < equation.length(); i++)
{
if (isdigit(equation[i]))
{
stack.push(equation[i]);
count++;
}
else
{
oparray = new int [count];
for (int o = 0; o < count; o++)
{
oparray[o] = stack.getTop();
stack.pop();
}
switch(equation[i])
{
case '+':
for (int i =0; i < count; i++)
{
op += oparray[i];
count--;
}
stack.push(op);
break;
case '-':
for (int i =0; i < count; i++)
{
op-=oparray[i];
count--;
}
stack.push(op);
break;
case '*':
for (int i =0; i < count; i++)
{
op*=oparray[i];
count--;
}
stack.push(op);
break;
case '/':
for (int i =0; i < count; i++)
{
op/=oparray[i];
count--;
}
stack.push(op);
break;
}
delete [] oparray;
}
}
result = stack.getTop();
cout << result;
}
I know I should not use the "using namespace std;", I was in a hurry. I doubt that would be the cause of my problems. Any help is greatly appreciated.
Your stack class has miscellaneous problems already pointed out in the comments. With those fixed, only a few bugs in the main program remained.
I've used a std::unique_ptr<> in your array instead of a raw pointer and disabled move semantics so it's neither copyable (because of the unique_ptr) nor moveable.
I also added throwing exceptions if you try to access the stack out of bounds.
#include <cctype>
#include <cstddef>
#include <exception>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
template<typename T>
class aStack {
public:
using value_type = T;
explicit aStack(size_t c) :
cap(c), stored(0), stack(std::make_unique<value_type[]>(cap)) {}
aStack(aStack&&) = delete; // moving disabled
void reset() noexcept { stored = 0; }
void push(const value_type& v) {
if(stored == cap) throw std::runtime_error("stack is full");
stack[stored++] = v;
}
void push(value_type&& v) {
if(stored == cap) throw std::runtime_error("stack is full");
stack[stored++] = std::move(v);
}
value_type& pop() {
if(stored == 0) throw std::runtime_error("stack is empty");
return stack[--stored];
}
[[nodiscard]] const value_type& top() const {
if(stored == 0) throw std::runtime_error("stack is empty");
return stack[stored - 1];
}
[[nodiscard]] value_type& top() {
if(stored == 0) throw std::runtime_error("stack is empty");
return stack[stored - 1];
}
[[nodiscard]] size_t capability() const noexcept { return cap; }
[[nodiscard]] size_t size() const noexcept { return stored; }
private:
size_t cap, stored;
std::unique_ptr<value_type[]> stack;
};
When it comes to the main program, the major problem was that you forgot to convert the ASCII value of each digit into an integer.
Another problem was the op calculation. You kept the value from the last iteration instead of grabbing a new value from the stack. There was also an extra allocation of memory that was unnecessary so I removed that. You also had shadowing variables, which didn't cause any error, but makes it really hard to read the code.
int main(int argc, char* argv[]) {
if(argc < 2) {
std::cout << "USAGE: " << argv[0] << " <equation>\n";
return 1;
}
std::string equation(argv[1]);
try {
int op, result;
aStack<int> stack(equation.length());
for(size_t ei = 0; ei < equation.length(); ++ei) {
if(std::isdigit(equation[ei])) {
stack.push(equation[ei] - '0'); // from ASCII to digit
} else {
op = stack.pop(); // start with what's on the stack
switch(equation[ei]) {
case '+':
while(stack.size()) {
op += stack.pop();
}
stack.push(op);
break;
case '-':
while(stack.size()) {
op -= stack.pop();
}
stack.push(op);
break;
case '*':
while(stack.size()) {
op *= stack.pop();
}
stack.push(op);
break;
case '/':
while(stack.size()) {
op /= stack.pop();
}
stack.push(op);
break;
default:
throw std::runtime_error("invalid operation");
}
}
}
result = stack.pop();
if(stack.size() != 0)
throw std::runtime_error("stack not empty when calculation ended");
std::cout << result << '\n';
} catch(const std::exception& ex) {
std::cerr << "Exception: " << ex.what() << '\n';
}
}
Related
I am trying to find the minimum vertex cover by giving the vertex and edge input in specific format from the user using threads. Here is my code:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>
#include <list>
#include <set>
#include <vector>
#include <climits>
#include <memory>
#include <algorithm>
#include <pthread.h>
#include <unistd.h>
#include "minisat/core/Solver.h"
using namespace std;
static void *AVC2_Vertex_Cover(void *);
void min_vertex_cover_algorithm(Graph &graph_builder){
int ret;
pthread_t AVC2_thread;
ret = pthread_create(&AVC2_thread, NULL, AVC2_Vertex_Cover, &graph_builder);
if(ret)
exit(1);
pthread_join(AVC2_thread, NULL);
pthread_exit(NULL);
}
struct Edge{
unsigned v1,v2;
};
typedef std::vector<unsigned> Vertex_vector;
typedef std::list<unsigned > Vertex_Adjacency_list;
typedef std::vector<Vertex_Adjacency_list> Adjacency_Traversal_list;
struct Graph{
std::size_t no_of_edges;
Adjacency_Traversal_list adjacency_list;
void initialize_graph(unsigned vertices_number);
void construct_edge(Edge edge);
void clear(unsigned vertex);
};
void Graph::initialize_graph(unsigned num){
adjacency_list.clear();
no_of_edges = 0;
adjacency_list.resize(num,{});
}
void Graph::construct_edge(Edge edge) {
auto &literal_1 = adjacency_list[edge.v1];
auto &literal_2 = adjacency_list[edge.v2];
literal_1.push_back(edge.v2);
literal_2.push_back(edge.v1);
no_of_edges ++;
}
void *AVC2_Vertex_Cover(void *input)
{
Graph g = *(const Graph *)input;
unsigned int V = g.adjacency_list.size();
bool visited[V];
for (int i=0; i<V; i++)
visited[i] = false;
for (int u=0; u<V; u++)
{
if (visited[u] == false)
{
for(int x : g.adjacency_list[u])
{
int v = x;
if (visited[v] == false)
{
visited[v] = true;
visited[u] = true;
break;
}
}
}
}
// Print the vertex cover
std::cout << "APPROX-VC-2: ";
for (int i=0; i<V; i++){
if (visited[i])
if(i == V-1)
cout << i << std::endl;
else
cout << i << ",";
}
}
void *IO_thread(void *)
{
Graph &graph_builder = *new Graph();
char character_input;
string my_input;
unsigned int no_of_vertices = 0;
string edge_stream;
char prev_choice = ' ';
while (getline(cin, my_input))
{
istringstream stream_string(my_input);
while (stream_string >> character_input)
{
character_input=(toupper(character_input));
try
{
switch (character_input)
{
case 'V' :
if (prev_choice == 'V')
{
cerr << "Error: V must be followed by E only.\n";
break;
}
else
{
stream_string >> no_of_vertices;
if(no_of_vertices <= 0)
{
throw "Invalid number of vertices";
}
graph_builder.initialize_graph(no_of_vertices);
prev_choice = 'V';
break;
}
case 'E' :
{
unsigned int flag_Entry = 0;
if ( prev_choice == 'E')
{
cerr << "Error: V and E always occur together.\n ";
break;
}
else
{
stream_string >> edge_stream;
istringstream edge_stream_character(edge_stream);
char edg_char;
unsigned int temp = 0;
unsigned int v1;
unsigned int v2;
edge_stream_character >> edg_char;
while (edg_char != '}')
{
edge_stream_character >> edg_char;
if (edg_char == '}')
{
flag_Entry = 1;
break;
}
else
{
edge_stream_character >> temp;
v1 = temp;
edge_stream_character >> edg_char;
edge_stream_character >> temp;
v2 = temp;
edge_stream_character >> edg_char;
edge_stream_character >> edg_char;
if (v1 >= no_of_vertices || v2 >= no_of_vertices)
{
cerr << "Error: Vertex out of range.\n";
graph_builder.adjacency_list.clear();
break;
}
graph_builder.construct_edge({v1,v2});
}
}
if(flag_Entry == 1)
{
prev_choice = 'E';
break;
}
min_vertex_cover_algorithm(graph_builder);
prev_choice = 'E';
break;
}
}
}
}
catch (const char* err)
{
cerr << "Error:" << err << endl;
}
}
}
return 0;
}
int main(int argc, char **argv){
int ret;
pthread_t IO_thread;
ret = pthread_create(&IO_thread, NULL, IO_thread,NULL);
if(ret)
return 1;
pthread_join(IO_thread,NULL);
pthread_exit(NULL);
}
I am getting an error:
unknown type name 'Graph'
void min_vertex_cover_algorithm(Graph &graph_builder){
I am not able to find why this error is occuring. It will be very helpful if I get some solutions.
Just like you, the compiler will read from top to bottom. When it reaches the line:
void min_vertex_cover_algorithm(Graph &graph_builder){
It has to go, ok, lets use a Graph reference. It will look for the declaration of a Graph, which it cannot find, because you have declared (and defined) it below. To solve this, give the compiler a hint. Declare the Graph above the function with:
struct Graph;
void min_vertex_cover_algorithm(Graph &graph_builder){
Or simply move the whole struct definition above the function.
This is a Stack class based on a dynamic array of struct for Depth First Search (DFS). The program is not able to run whenever it encounters the function, push(), which shows that the array is not successfully initialized in the constructor.
I have tried to look for the error and even changing the dynamic array of struct into parallel arrays but it still does not work. I apologize if the problem seems to be too simple to be solved as I do not have a strong foundation in C++.
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
I expect it to run well but an exception is always thrown on line 80, which is as follows:
Exception thrown at 0x00007FF6A160487C in Assignment1.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
The problem is this line right here:
Value * array = new Value[size];
This declares a new array variable. You are allocating that array instead, and not your member variable array.
The answer is simple, just change it to this instead:
array = new Value[size];
My code compiles successfully, but when I try to run it, I keep getting this error: * Error in `./a.out': corrupted double-linked list: 0x00000000021c1280 *
Aborted
This is my VectorDouble.cpp file
#include<bits/stdc++.h>
#include <cstring>
#include "VectorDouble.h"
#include <iostream>
using namespace std;
VectorDouble::VectorDouble() {
cout<<"constructor called"<<endl;
max_count = 50;
arr = new double[this->max_count];
count = 0;
}
VectorDouble::VectorDouble(int max_count_arg) {
max_count = max_count_arg;
arr = new double[max_count_arg];
count = 0;
}
VectorDouble::VectorDouble(const VectorDouble& copy) {
max_count = copy.max_count;
arr = new double[this->max_count];
count = copy.count;
}
VectorDouble::~VectorDouble() {
delete []arr;
}
VectorDouble VectorDouble::operator =(VectorDouble& copy) {
VectorDouble temp(copy.max_count);
for(int i =0; i<=this->count;i++){
temp.arr[i]=copy.arr[i];
}
return temp;
}
bool VectorDouble::operator ==(VectorDouble b) const {
bool isEqual = true;
if(this->count == b.count){
for(int i = 0; i<=this->count; i++){
if(this->arr[i] == b.arr[i]){
isEqual= true;
}
else{
return false;
}
}
}
return isEqual;
}
void VectorDouble::push_back(double num) {
if(this->count+1>this->max_count){
this->max_count *= 2;
VectorDouble temp(2*(this->max_count));
for(int i = 0; i<this->max_count; i++){
temp.arr[i]=this->arr[i+1];
}
temp.arr[count+1] = num;
}
else{
this->arr[count+1]=num;
this->count++;
}
}
int VectorDouble::capacity() {
return this->max_count;
}
int VectorDouble::size() {
return this->count;
}
void VectorDouble::resize(unsigned int size, double defaultVal) {
if(size>(this->count)){
for(int i = this->count; i<size; i++){
this->arr[i] = defaultVal;
}
this->count=size;
}
else{
for(int i = size; i < this->count; i++){
this->arr[i] ='\0';
}
this->count=size;
}
}
void VectorDouble::reserve(unsigned int size) {
if(size>(this->max_count)){
this->max_count = size;
}
}
double VectorDouble::value_at(unsigned int i) {
if(i>(this->count)){
throw std::logic_error("out of bounds");
}
return this->arr[i];
}
void VectorDouble::change_value_at(double newValue, unsigned int i) {
if(i>(this->count)){
throw std::logic_error("out of bounds");
}
this->arr[i]=newValue;
}
ostream& operator<<(ostream& os, const VectorDouble &vd)
{
for(int i = 0; i < vd.count; i++){
os << vd.arr[i] << " ";
}
return os;
}
This is my VectorDouble.h file
#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include <iostream>
using namespace std;
class VectorDouble {
public:
int max_count;
int count;
double* arr;
public:
VectorDouble();
VectorDouble(int max_count_arg);
VectorDouble(const VectorDouble& copy);
~VectorDouble();
VectorDouble operator =(VectorDouble& copy);
bool operator ==(VectorDouble b) const;
void push_back(double num);
int capacity();
int size();
void reserve(unsigned int size);
void resize(unsigned size, double defaultVal = 0.0);
double value_at(unsigned int i);
void change_value_at(double newValue, unsigned int i);
friend ostream& operator<<(ostream& os, const VectorDouble &vd);
// DO NOT CHANGE THE FOLLOWING LINE OF CODE. It is for the testing framework
// DO NOT IMPLEMENT THE FOLLOWING FUNCTION. It is implemented by the testing framework
friend int reserved_driver_main();
};
#endif
This is my main.cpp file
#include <iostream>
#include "VectorDouble.h"
using namespace std;
int user_main() {
// test 1, verify that default constructor initializes max_count
VectorDouble v;
if (v.max_count == 50)
{
std::cout << "1.1. default constructor: max_count = 50; test passed" << std::endl;
}
else
{
std::cout << "1.1. default constructor: max_count != 50; test failed" << std::endl;
}
return 0;
}
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;
}
So I have such definition on map class on vector, it works good except for post-incrementation, which doesn't work as it should. You can see in example that variable a should be equal to 10 (post-incremented after assignment). But it's equal to 11. I have no idea how to fix that.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<class T>
class Map {
class Cref {
friend class Map;
Map& m;
string key;
T value;
public:
operator double() {
return m.read(key);
};
Map::Cref & operator=(double num) {
m.write(key, num);
return *this;
};
Map::Cref & operator++(int) {
Cref c(*this);
m.increment(key, value);
return c;
}
Cref(Map& m, string a)
: m(m),
key(a) {};
};
public:
class Unitialized {};
struct Record {
string key;
T value;
};
vector<Record> data;
Map() {}
~Map() {}
bool ifexist(string k) {
for (int i = 0; i < data.size(); i++) {
if (data.at(i).key == k)
return 1;
}
return 0;
}
Cref operator[](string key) {
return Map::Cref( * this, key);
}
private:
void increment(string key, T value) {
if (ifexist(key) == 0) {
throw Unitialized();
}
for (int i = 0; i < data.size(); i++) {
if (data.at(i).key == key)
data.at(i).value += 1;
}
}
void write(string key, T value) {
if (ifexist(key) == 1) {
cout << "Element already exist" << endl;
return;
}
Record r;
r.key = key;
r.value = value;
data.push_back(r);
}
double read(string key) {
if (ifexist(key) == 0) {
throw Unitialized();
}
for (int i = 0; i < data.size(); i++) {
if (data.at(i).key == key)
return data.at(i).value;
}
return 0;
}
};
int main(int argc, char** argv) {
Map<int> m;
m["ala"] = 10;
int a = 0;
a = m["ala"]++;
cout << a << endl;
try {
cout << m["ala"] << endl;
cout << m["ola"] << endl;
} catch (Map<int>::Unitialized&) {
cout << "Unitialized element" << endl;
}
return 0;
}
Yes, I already fixed that, overloading of ++ operator should look like that :
T operator ++(int)
{
T ret = m.read(this->key);
m.increment(key, value);
return ret;
}
This fixes everything.