我为我的类制作了一个模板来模拟堆栈的基本功能,但我收到了一个错误,但我不知道如何修复它。
我的代码:
#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();
}
错误发生在运行时,它表示它访问了不应该访问的内存。 另外我想知道是否可以通过类似 stack *st = new stack(n, &v) 的指针来声明我的堆栈。这可能吗?
最佳答案
你的构造函数完全是倒退的:
template<class T>
stack<T>::stack(int x, vector<T> *y)
{
n = x;
v = y;
}
关于C++ 堆栈模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8964081/