我正在做一个数据结构练习,从昨天开始我就因为总线错误而被阻塞了,我认为这是因为我对内存做了坏事。但我无法弄清楚到底是什么。
这些是我为实践建立的要求:
- 能够将产品(任何方式都可以)添加到列表中
- 能够在当前位置检索列表中的产品(next、prev、moveToStart、moveToEnd……有光标指针,这里称为“实际”)
- 我对检索到的产品所做的任何更改都应在数据结构中更新(即 list::retrieve(*product)、product->visits++)
这是我拥有的代码。关于 var 名称的道歉,我必须用西班牙语做,因此名称是西班牙语。
class producto { // My product
public:
string marca;
double precio;
int visitas;
int compras;
producto () {}
producto (string M, double P, int V = 0, int C = 0) : marca(M), precio(P), visitas(V), compras(C) {}
};
class nodo {
public:
producto valor; // value
nodo *siguiente; // next
nodo *anterior; // prev
nodo (producto P, nodo *A = NULL, nodo *S = NULL) : valor(P), anterior(A), siguiente(S) {}
};
class lista {
private:
nodo *inicio;
nodo *final;
nodo *actual;
public:
lista();
bool esta_vacia(); // is empty?
bool es_final(); // is the end?
int insertar(producto p); // insert given p
void moverPrincipio(); // "move to beginning"
void siguiente(); // "next"
void imprimir(); // "print"
int leer(producto *p); // read, return 0 or 1 if successful, return product by ref
};
lista::lista() {
this->inicio = NULL;
this->final = NULL;
this->actual = NULL;
}
bool lista::esta_vacia() {
return (this->inicio == NULL);
}
bool lista::es_final() {
return (this->actual == NULL);
}
void lista::moverPrincipio() {
this->actual = this->inicio;
}
void lista::siguiente() {
if(!this->es_final()) {
this->actual = this->actual->siguiente;
}
}
void lista::imprimir() {
int i = 1;
producto *p;
this->moverPrincipio();
while(!this->es_final()) {
if(this->leer(p) == 0) {
cout << i << ".- ##" << p->marca << "##, Views ##" << p->visitas << "##\n";
p->visitas++;
i++;
this->siguiente();
}
}
}
int lista::leer(producto *p) {
if(this->actual != NULL) {
*p = this->actual->valor;
return 0;
} else {
return 1;
}
}
int lista::insertar(producto p) {
if(this->esta_vacia()) {
nodo *tmp = new nodo(p);
this->inicio = tmp;
this->final = this->inicio;
} else {
nodo *tmp = new nodo(p, this->final);
this->final->siguiente = tmp;
this->final = tmp;
}
return 0;
}
我已经删除了不必要的代码。这就是我使用它的方式(并且失败得很惨):
lista *productos = new lista();
productos->insertar(producto("Shoes", 19.90));
productos->insertar(producto("Socks", 25.00));
// I should expect views = 0
productos->imprimir();
// But now, views = 1
productos->imprimir();
执行后,第一次执行 imprimir(“打印”)时,我得到的唯一结果是“总线错误:10”。插入工作没有错误(但那里也可能有问题)。
我的想法是将产品保存在节点内,并在返回时引用其位置,以便任何更改也反映在那里(例如,增加检索元素的查看或购买计数器,在阅读时反映更改稍后列出)。
如果有人能指出我在这里做的错误,我将非常感激。
谢谢!!
更新 这是一个可编译的示例。