我有这个结构:
struct Node {
int number;
Node *next;
};
这个类用于插入元素并显示 vector :
// Classe DynamicVector :
// e' la classe che consente di inserire elementi
// e visualizzare il vettore di strutture
class DynamicVector
{
public:
DynamicVector();
void InsertNumber(int number);
void ShowVector();
protected:
Node *p;
};
这是实现:
DynamicVector::DynamicVector() {
this->p = NULL;
}
void DynamicVector::InsertNumber(int number) {
Node *temporary = new Node;
// Possiamo avere due possibili casi:
// non e' stato ancora inserito nessun elemento
// ...
if (this->p == NULL) {
temporary->number = number;
temporary->next = NULL;
this->p = temporary;
// ...
// oppure dobbiamo aggiungerne uno alla fine
// In questo caso meglio dire, lo "accodiamo"
} else {
// Sfogliamo le strutture fino a giungere
// all' ultima creata
while (this->p->next != NULL) {
this->p = this->p->next;
}
temporary->number = number;
temporary->next = NULL;
// In questo passaggio copiamo la struttura
// temporanea "temporary" nell' ultima struttura "p"
this->p->next = temporary;
}
}
void DynamicVector::ShowVector() {
while (this->p != NULL) {
std::cout << this->p->number << std::endl;
this->p = this->p->next;
}
}
在主函数中我这样写:
#include <iostream>
#include <conio.h>
#include "dynamic_vector.h"
int main() {
DynamicVector *vector = new DynamicVector();
vector->InsertNumber(5);
vector->InsertNumber(3);
vector->InsertNumber(6);
vector->InsertNumber(22);
vector->ShowVector();
delete vector;
getch();
return 0;
}
我不知道为什么,但它只显示最后两个数字。 有人知道为什么吗?
最佳答案
它只显示最后两个数字,因为当您插入新数字时,您正在将头部移动到下一个节点。您有两种选择来打印整个 vector 。
if (this->p == NULL) {
temporary->number = number;
temporary->next = NULL;
this->p = temporary;
// ...
// oppure dobbiamo aggiungerne uno alla fine
// In questo caso meglio dire, lo "accodiamo"
} else {
// Sfogliamo le strutture fino a giungere
// all' ultima creata
Node* temp2 = this->p;
while (temp2->next != NULL) {
temp2 = temp2->next;
}
temporary->number = number;
temporary->next = NULL;
// In questo passaggio copiamo la struttura
// temporanea "temporary" nell' ultima struttura "p"
temp2->next = temporary;
}
或者在 main() 中,存储 vector 第一个节点的位置,并将其用于打印
DynamicVector *vector = new DynamicVector();
DynamicVector *vector2 = vector;
...
vector2->ShowVector();
关于c++ - 使用 Struct 的动态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13806983/