c++ - 使用 Struct 的动态 vector

标签 c++ dynamic vector struct

我有这个结构:

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/

相关文章:

c++ - 二维数组动态分配C++

excel - 使用 Excel 仅将唯一列转置为标题行

c++ - 如何使用 std::vector<std::tuple<A,B>> 来管理内存(调整大小、保留...),但实际上保持 B 之前的 As 连续

作为向量的 Clojure 惰性序列

java - Initialization On Demand Holder 成语

c++ - #import 等效命令行

javascript - 插入到 DOM 的元素中未触发 Onclick

C++逐字符读取二进制文件

c++ - 为什么ofstream作为类成员不能传递给thread?

c++ - 如何理解 "vector<int> avector (arr, arr + sizeof(arr)/sizeof(arr[0]) )"?