【发布时间】:2019-11-22 01:15:28
【问题描述】:
我必须从文件 100 中读取不同类型的任务,以便对队列执行不同的操作,并在输出文件上打印。 但是我得到“在抛出'std :: bad_alloc'的实例后调用终止” 作为错误 我认为是模板声明中的内容。 我试图以不同的方式声明它,但似乎不起作用。 如果有人可以帮助我,我将非常感激。
#include <iostream>
#include <fstream>
#include <string>
#define INPUT_FILE "input.txt"
#define OUTPUT_FILE "output.txt"
using namespace std;
template <typename T> class Pila
{
private:
bool empty=1;
public:
int lunghezza;
int cima;
T * Tab;
Pila(int L){
lunghezza=L;
Tab= new T[L];
cima=lunghezza;
}
void Push(T L){
cima--;
Tab[cima]=L;
}
void Pop(){
if(!empty)
cima++;
if(cima=lunghezza) empty=1;
}
bool Empty(){
if(empty==1) return 1;
else return 0;
}
T top(){
return Tab[cima];
}
void Print(){
for(int i=lunghezza-1; i>=cima; i--) cout<< Tab[i]<< " ";
}
};
template <typename V> class Queue
{
public:
int lunghezza;
Queue(int l){
lunghezza=l;
};
Pila<V> A= Pila <V>(lunghezza);
Pila<V> B= Pila <V>(lunghezza);
void enqueue(V L){ //sposta tutti gli elementi da A a B
while(!A.Empty()){
B.Push(A.top());
A.Pop();
}
A.Push(L); //Mette L dentro A
while(!B.Empty()){ //sposta tutto di nuovo dentro A
A.Push(B.top());
B.Pop();
}
}
void dequeue(){
if(A.Empty()){
cout<< " Coda Vuota"<< endl;
}
else
A.Pop();
}
void Stampa(){
A.Print();
cout<< endl;
}
};
int main(){
fstream infile, outfile;
infile.open(INPUT_FILE, fstream::in);
outfile.open(OUTPUT_FILE, fstream::out);
int c=0, N,tmp;
string tipo,operazione;
while(c<100){
infile>> tipo;
infile>> N;
if(tipo=="int"){
Queue<int> A(N);
for(int i=0; i<N; i++){
infile>> operazione;
if(operazione=="dequeue")
A.dequeue();
else
{
int elem=stoi(operazione.substr(1));
A.enqueue(elem);
}
}
A.Stampa();
}
if(tipo=="double"){
Queue<double> A(N);
for(int i=0; i<N; i++){
infile>> operazione;
if(operazione=="dequeue")
A.dequeue();
else
{
double elem=stod(operazione.substr(1));
A.enqueue(elem);
}
}
A.Stampa();
}
if(tipo=="bool"){
Queue<bool> A(N);
for(int i=0; i<N; i++){
infile>> operazione;
if(operazione=="dequeue")
A.dequeue();
else
{
bool elem=stoi(operazione.substr(1));
A.enqueue(elem);
}
}
A.Stampa();
}
if(tipo=="char"){
Queue<char> A(N);
for(int i=0; i<N; i++){
infile>> operazione;
if(operazione=="dequeue")
A.dequeue();
else
{
char elem=(char)(operazione[1]);
A.enqueue(elem);
}
}
A.Stampa();
}
c++;
}
}
【问题讨论】:
-
离题:习惯于在代码中使用纯英文标识符。您将与不懂意大利语的人共享代码,如果只是在这里。了解变量的用途将有助于他们更好/更快地理解您的代码,并且您可能会更快地获得更好的响应......
-
您正在泄漏 很多 内存。我猜它最终会用完,因此会抛出
std::bad_alloc。 -
这是相当多的代码需要检查和调试。你能把它简化为一个更简单的例子吗?也许是直接操纵你的 Pila 和 Queue 对象的东西?
-
std::bad_alloc表示内存分配失败。也许您正在尝试分配过多的内存? -
Pila(int L) { Tab= new T[L]; }- 如果你在创建时分配,你需要在销毁时销毁,即。 e.您还需要一个自定义析构函数。但是再考虑three 和five 的规则!更简单的解决方案:改用smart pointer。