I've this struct:
struct Node {
int number;
Node *next;
};
and this class to insert element and show the 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;
};
This is the implementation:
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;
}
}
In the main function I wrote this:
#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;
}
I dont' know why but it show me only the last two number. Someone know why?
std::vectoras it is a dynamic vector and has been throroughly debugged. Which means you don't have to waste time debugging it.DynamicVectoron the heap instead of taking advantage of RAII by letting it reside on the stack?