I made a template for my class to emulate the basics functions of the stack and I’m getting an error and i don’t know how to fix it.
My code:
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class stack
{
vector<T> *v;
int n;
public:
stack(int,vector<T>*);
~stack();
void push(T);
void pop();
void afis();
};
template<class T>
stack<T>::stack(int x, vector<T> *y)
{
x = n;
y = v;
}
template<class T>
stack<T>::~stack()
{
}
template<class T>
void stack<T>::push(T item)
{
v->push_back(item);
}
template<class T>
void stack<T>::pop()
{
v->pop_back();
}
template<class T>
void stack<T>::afis()
{
typedef vector<T>::iterator it;
for(it i = v->begin(); i != v->end(); ++i)
cout << *i << " ";
}
int main()
{
int n, nr;
cin >> n;
vector<int> v;
for(int i = 0; i < n; i++)
{
cin >> nr;
v.push_back(nr);
}
stack<int> st(n, &v);
st.pop();
st.afis();
}
And the error is at runtime and it says it accessing memory that it shouldn’t.
Also I am wondering if i can declare my stack thru a pointer something like stack *st = new stack(n, &v). Is that posible?
Your constructor is all backwards: