I'm currently working with stack data structure in C++, and i'm trying to initialize the stack by using arrays.
Stack has a specific size and i want to print elements of the stack from top to bottom using for loop.
Here is my code:
#include <iostream>
using namespace std;
template<class T>
class Stack {
private:
int top, size;
T* stack = new T[size];
public:
Stack(int size) {
this->top = -1;
this->size = size;
}
void push(int data) {
if (top >= size - 1) {
return;
}
else {
++top;
stack[top] = data;
}
}
void pop() {
if (top < 0) {
return;
}
else {
--top;
}
}
void print() {
for (int i = top; i >= 0; i--) {
cout << stack[i] << endl;
}
}
};
int main() {
Stack<int> stack(20);
stack.push(12);
stack.push(3);
stack.push(4);
stack.push(7);
stack.print();
return 0;
}
After compiling i get all of my elements printed successfully, but unfortunately at the end the program throws an exception ntdll.pdb not loaded.
Thanks in advance.
The order of construction is wrong. The member variables are initialized before the constructor body is entered, so size contains an arbitrary value at that time it's read to determine the size of the array. Furthermore you forgot to delete the array.
To fix the initialization order, initialize the array in the constructor and add a destructor. In the following code I simply use std::unique_ptr which automatically deletes the array contained in it.
Furthermore it's preferrable to not use the same identifier for parameters and members; a prefix usually is added to member variables to avoid this
#include <memory>
...
template<class T>
class Stack {
private:
size_t m_size;
int m_top;
std::unique_ptr<T[]> m_stack;
public:
Stack(size_t size)
: m_stack(new T[size]), m_size(size), m_top(-1)
{
}
...
Related
I'm attempting to implement an intvector in C++ and am getting a "Segmentation fault: 11" error. I understand this has something to do with memory management, and considering how new I am to C++ it could definitely be a pretty minor mistake. I debugged the code with valgrind and was given messages such as the following:
Use of uninitialized value of size 8, Invalid read of size 4,Conditional jump or move depends on uninitialized value(s).
My best guess is it has something to do with how I'm implementing the arrays. I originally had the arrays stored on the heap but changed it to the stack and still got the same error. I've already implemented an intvector in java, so I was attempting to use similar logic here, which perhaps is part of the issue.
#include <iostream>
#include "IntVector.h"
#include <cmath>
using namespace std;
int num_elements = 0;
int array_size = 0;
int expansion_factor;
void IntVector::expandArray(){
int tempArr[array_size*2];
for(int i =0;i<array_size;i++){
tempArr[i] = array[i];
}
array = tempArr;
array_size = array_size * 2;
}
void IntVector::add(int val){
int tempArr[array_size];
if(array_size == num_elements){
expandArray();
array[num_elements] = val;
}
else{
for(int i = 0;i<array_size;i++){
tempArr[i] = array[i];
}
tempArr[num_elements] = val;
array = tempArr;
}
num_elements++;
}
void IntVector::remove(int index){
}
int IntVector::get(int index) const{
return index;
}
void IntVector::removeLast(){
}
void IntVector::set(int index, int val){
}
std::string IntVector::toString()const {
return "";
}
IntVector::IntVector(int initial_size){
int* array = new int[initial_size];
}
IntVector:: ~IntVector(){
delete[] array;
}
int main(){
IntVector v(0);
v.add(5);
}
#ifndef INTVECTOR_H_
#define INTVECTOR_H_
using std::cout;
class IntVector {
private:
int* array;
int num_elements;
int array_size;
int expansion_factor;
void expandArray();
public:
void add(int val);
void remove(int index);
int get(int index) const;
void removeLast();
void set(int index, int val);
std::string toString() const;
IntVector(int initial_size);
~IntVector();
};
#endif
As mention in the comments, there are definitely some holes in your understanding of C++. Really when dealing with header files you should have a main.cpp, someotherfile.h, someotherfile.cpp. That just best practices to avoid redefinition errors.
There was quite a bit wrong with the way you accessed the private variable. If a class has a private( or even public) variable you don't have to redeclare it each time you want to change its value.
There were one or two major flaws with the way you expanded the vector. If the vector size is initialized to 0 then 0*2 is still 0 so you never actually increased the size. Secondly, when you set the original array = to the new array the new array was just a local array. This means that the memory wasn't actually allocated permanently, once the function ended the temparr was destroyed.
I know this was probably a lot but if you have any question feel free to ask.
main.cpp
#include "IntVector.h"
int main()
{
IntVector v;
IntVector x(10);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.print();
cout << endl;
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.print();
return 0;
}
IntVector.h
#include <string>
#include <iostream>
using namespace std;
class IntVector {
private:
int *array;
int num_elements;
int array_size;
//int expansion_factor =; you would only need this if you plan on more than double the vector size
void expandArray(); //normally c++ array double in size each time they expand
public:
//Constructors
IntVector(); //this is a contructor for if nothing is called
IntVector(int initial_size);
//setters
void push(int val); //add
void pop(); //removelast
void remove(int index); //remove
void at(int index, int val); //set
//Getters
int at(int index);
//std::string toString(); I'm changing this to print
void print(); //will print the contents to the terminal
//Deconstructor
~IntVector();
};
IntVector.cpp
#include "IntVector.h"
//constructors
IntVector::IntVector() //no arguments given
{
array = new int[0];
num_elements = 0;
array_size = 0;
}
IntVector::IntVector(int initial_size)
{
array = new int[initial_size];
num_elements = 0;
array_size = initial_size;
}
void IntVector::expandArray()
{
int *tempArr;
if(array_size == 0){
array_size = 1;
tempArr = new int[1];
} else {
//make sure to allocate new memory
//you were creating a local array which was destroy after the function was completed
//using new will allow the array to exist outside the function
tempArr = new int[array_size * 2];
}
for (int i = 0; i < array_size; i++)
{
tempArr[i] = array[i];
}
//make sure to delete the old array otherwise there is a memory leak.
//c++ doesn't have a garbage collector
delete[] array;
array = tempArr;
array_size = array_size * 2;
}
void IntVector::push(int val)
{
num_elements++;
//checking if vector needs to increase
if (array_size <= num_elements)
{
expandArray();
array[num_elements-1] = val;
}
else
{
array[num_elements-1] = val;
}
}
void IntVector::remove(int index)
{
//not sure how to implment this becuase each element has to be a number.
}
int IntVector::at(int index)
{
return array[index];
}
void IntVector::pop()
{
num_elements = num_elements-1; //not really removing it from the "vector" but it won't print out again
}
void IntVector::at(int index, int val)
{
array[index] = val;
}
void IntVector::print()
{
for (int i = 0 ; i < num_elements; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
IntVector::~IntVector()
{
delete[] array;
}
output
5 5 5 5 5
5 5 5 5 5
Hopefully, the comments help. I changed the name of the functions to better match the actual vecter class the already exists in C++. I think it's good to pick apart already defined functions like this because you get a better understanding of how they actually work and not just how to use them.
If you got any questions just leave a comment
In the class constructor, I am initializing other objects and pushing these objects to my class vector member. From what I understand, the vector create a copy of the object and stores it so that it doesn't go out of scope. However, when verifying the objects in another class function, they are not initialized anymore. Here's a example code to explain the behaviour:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Square {
private:
int size_ = 0;
int colour_ = 0;
public:
Square(){
size_ = 0;
colour_ = 0;
}
void init(int size, int colour) {
size_ = size;
colour_ = colour;
}
int get_size() { return size_; }
};
class SetSquares {
private:
std::vector<Square> squares_;
int number_;
public:
SetSquares(): number_(0) {}
void init(int num) {
number_ = num;
squares_.clear();
squares_.resize(num);
for (int i=0; i < num; i++) {
Square square;
square.init(i, i);
squares_.push_back(square);
}
}
void sample(int i) {
if (i >= number_) { return; }
std::cout << "Square size is: " << squares_[i].get_size() << std::endl;
}
};
int main()
{
SetSquares set_of_squares;
set_of_squares.init(7);
set_of_squares.sample(4);
return 0;
}
resize(n) will create n default constructed elements in a vector and push_back will append new elements after those n elements. Use reserve and push_back or resize and index operator as suggested in comment.
#include <iostream>
#include <string.h>
using namespace std;
#define NMAX 10 // pre-processing directive
template<typename T>
class Stack {
public:
T Smain, Saux;
T stackArray[NMAX];
int topLevel;
int getTopLevel()
{
return this->topLevel;
}
void push(T x)
{
if (topLevel >= NMAX - 1)
{
cout<<"The stack is full: we have already NMAX elements!\n";
return;
}
stackArray[++topLevel] = x;
}
int isEmpty()
{
return (topLevel < 0);
}
T pop()
{
if (isEmpty()) {
cout<<"The stack is empty! \n";
T x;
return x;
}
return stackArray[topLevel--];
}
T peek()
{
if (isEmpty())
{
cout<<"The stack is empty! \n";
T x;
return x;
}
return stackArray[topLevel];
}
void afficher() {
cout<<"On affiche la pile:";
for ( int i=0; i<=topLevel; i++ )
cout<<stackArray[i]<<" ";
cout<<endl;
}
Stack()
{
topLevel = -1;
}
~Stack() {
}
void change(int i)
{
while (Smain.topLevel>i){
Saux.push(Smain.pop());}
T aux1=Smain.pop();
T aux2=Smain.pop();
Smain.push(aux1);
Smain.push(aux2);
while (Saux.topLevel>=0){
Smain.push(Saux.pop());}
}
};
int main()
{
Stack<int> stack1;
Stack<int> stack2;
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.push(4);
change(3);
stack1.afficher();
return 0;
}
This program has to swap the i and i-1 position of a stack, but i get the error: 'change' was not declared in this scope and i don't know how to make it work. please help me and thanks to you in advance.
change is declared inside the class Stack, so it becomes a method on a Stack instance.
You probably want to call it as stack1.change(3) instead.
You cannot call change() function which is inside a class directly.instead use an class object to call it.
class stack{
}objectname;
int main(){
objectname.change(3);
}
I am running through an example of a static stack implementation from a book, but was not able to obtain the correct value for the last integer popped of the stack. Particularly, the pop(int &) member function in the class IntStack is said to pop the last integer off the stack, and take as input the name of a reference to the integer value that was just "popped".
Upon compiling the code, I find that the input is assigned the value of the address rather than the integer value. I am unsure why this happens, and I am also unsure how the pop member function of the IntStack class assigns this input to the last value stored at index "top."
I've posted the class files for reference (copied from the book - note that these are 2 separate files, one header and one *.cpp). Any help understanding this is soooo greatly appreciated!!!!!
#include <stdio.h>
// Specification file for the IntStack class
#ifndef INTSTACK_H
#define INTSTACK_H
class IntStack
{
private:
int *stackArray; // Pointer to the stack array
int stackSize;
int top;
public:
// The stack size
// Indicates the top of the stack
// Constructor
IntStack(int);
// Copy constructor
IntStack(const IntStack &);
// Destructor
~IntStack();
// Stack operations
void push(int);
void pop(int &);
bool isFull() const;
bool isEmpty() const;
};
#endif
// Implementation file for the IntStack class
#include <iostream>
#include "IntStack.h"
using namespace std;
//************************************************
// Constructor *
// This constructor creates an empty stack. The *
// size parameter is the size of the stack. *
//************************************************
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
//***********************************************
// Copy constructor *
//***********************************************
IntStack::IntStack(const IntStack &obj)
{
// Create the stack array.
if (obj.stackSize > 0)
stackArray = new int[obj.stackSize];
else
stackArray = nullptr;
// Copy the stackSize attribute.
stackSize = obj.stackSize;
// Copy the stack contents.
for (int count = 0; count < stackSize; count++)
stackArray[count] = obj.stackArray[count];
// Set the top of the stack.
top = obj.top;
}
//***********************************************
// Destructor *
//***********************************************
IntStack::~IntStack()
{
delete [] stackArray;
}
//*************************************************
// Member function push pushes the argument onto *
// the stack. *
//*************************************************
void IntStack::push(int num)
{
if (isFull())
{
cout << "The stack is full.\n";
}
else
{
top++;
stackArray[top] = num;
}
}
//*****************************************************
// Member function pop pops the value at the top *
// of the stack off, and copies it into the variable *
// passed as an argument. *
//*****************************************************
void IntStack::pop(int &num) {
if (isEmpty())
{
cout << "The stack is empty.\n";
}
else
{
top--;
}
}
//***************************************************
// Member function isFull returns true if the stack *
// is full, or false otherwise. *
//***************************************************
bool IntStack::isFull() const
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
//*****************************************************
// Member function isEmpty returns true if the stack *
// is empty, or false otherwise. *
//*****************************************************
bool IntStack::isEmpty() const
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
pop method is missing num assignment
void IntStack::pop(int &num) {
if (isEmpty())
{
cout << "The stack is empty.\n";
}
else
{
num=stackArray[top];
top--;
}
}
I came across a exercise on the web, this is the text:
Write a class int_stack that will manage a stack of integers. The
integers values will be stored in a dynamically allocated array.
This class will propose the following member functions :
int_stack (int n) constructor that will dynamically allocate n
integers,
int_stack ( ) constructor allocating 20 integers,
~ int_stack ( ) destructor,
int empty ( ) the return value is 1 if the stack is empty, 0
otherwise,
int full ( ) the return value is 1 if the stack is full, 0 otherwise,
void operator < (int p) pushes (add) the p value on the stack,
int operator >(int p) returns (and remove) the value on the top of
the stack
I've tried to implement it, but the > (pull) operator won't work.
Here's my code:
int_stack.h
class int_stack
{
private:
int* stack;
unsigned int n, p;
void init(unsigned int n);
public:
int_stack(unsigned int n);
int_stack();
~int_stack();
int empty();
int full();
void operator <(int i);
int operator >(int i);
};
int_stack.cpp
#include "int_stack.h"
void int_stack::init(unsigned int n)
{
this->stack = new int[n];
this->p = 0;
}
int_stack::int_stack(unsigned int n)
{
this->init(n);
}
int_stack::int_stack()
{
this->init(20);
}
int_stack::~int_stack()
{
delete this->stack;
}
int int_stack::empty()
{
return (this->p == 0 ? 1 : 0);
}
int int_stack::full()
{
return (this->p == n-1 ? 1 : 0);
}
void int_stack::operator <(int i)
{
if (!this->full())
this->stack[p++] = i;
}
int int_stack::operator >(int i)
{
if(!this->empty())
return this->stack[p--];
return 0;
}
What am I doing wrong?
In addition to getting the indexing right, the class needs a copy constructor and an assignment operator. As written you'll get multiple deletes of the same data block:
int_stack s0;
int_stack s1(s0); // uh-oh
Both destructors will delete the array allocated by the constructor for s0.
There are several major flaws with you code:
Unless you want to resize the stack every time you push or pop something onto or off of it, respectively, you probably want to use a linked-list- or deque- style storage structure instead of a vector/array-style.
Overloading operator< and operator> to do what amounts to extraction and insertion is a terrible interface choice. I would urge against using operators for those operations:
void int_stack::push(int i)
{
// push an element onto the stack
}
int int_stack::pop()
{
// pop an element off of the stack
}
Because you are not implementing it as a linked-list or deque, when you go to push elements, you can (and eventually will) attempt to write outside the bounds of the memory you allocated.
Finally, you do not delete your stack properly. If you use new [], you must also use delete [].
The choice of interface is quite bad, but ignoring that fact consider what your members mean, in particular p. The index p refers to the location above the last added element. When you return the value in the pop operation you are reading the value from that location, but that location does not have a value:
int int_stack::operator >(int i)
{
if(!this->empty())
return this->stack[p--]; // <-- predecrement!
return 0;
}
Regarding the interface, operator< and operator> are unnatural choices for the push and pop operations. When someone reads in code s < 5 they interpret that you are comparing s with 5, not inserting an element into the stack s. That is going to be the source of confusion.
Worse than operator< is operator> defined as int operator>(int). User code to read a value will end up looking as:
value = s > 5;
That looks like comparing s to 5, and storing the result into value. Moreover, the actual behavior is completely independent on the argument 5, the same operation can be spelled as s > -1 or even s > 5.3
Here is the working implementation I came up with.
It implements a copy constructor and the assignment operator.
Also, the indexing works, and the interface has changed from the < and > operators to two simple push(int) and int pop() functions.
It throws exceptions when you try to push/pop over the boundaries.
int_stack.h
#include <exception>
class int_stack
{
private:
int* stack;
unsigned int n, p;
void init(unsigned int n);
void copy(int_stack& other);
public:
int_stack(unsigned int n);
int_stack();
int_stack(int_stack& other);
int_stack& operator=(int_stack& other);
~int_stack();
int empty();
int full();
void push(int i);
int pop();
class OutOfBoundariesException: public std::exception {};
};
int_stack.cpp
#include "int_stack.h"
void int_stack::init(unsigned int _n)
{
n = _n;
stack = new int[n];
p = 0;
}
int_stack::int_stack(unsigned int n)
{
init(n);
}
int_stack::int_stack()
{
init(20);
}
int_stack::int_stack(int_stack& other)
{
copy(other);
}
int_stack& int_stack::operator=(int_stack& other)
{
copy(other);
return *this;
}
void int_stack::copy(int_stack& other)
{
n = other.n;
p = other.p;
stack = new int[n];
for (unsigned int i = 0; i < n; i++)
stack[i] = other.stack[i];
}
int_stack::~int_stack()
{
delete[] stack;
}
int int_stack::empty()
{
return (p == 0 ? 1 : 0);
}
int int_stack::full()
{
return (p == n ? 1 : 0);
}
void int_stack::push(int i)
{
if (!full())
stack[(++p)-1] = i;
else
throw new OutOfBoundariesException;
}
int int_stack::pop()
{
if (!empty())
return stack[(p--)-1];
else
throw new OutOfBoundariesException;
return 0;
}