c++中的结构是如何工作的

how do structures behave in c++

本文关键字:工作 何工作 结构 c++      更新时间:2023-10-16

我正在阅读下面的教程代码,当我被下面的代码卡住时:

#include <iostream>
#include <string>
using namespace std;
struct Node {
 int roll;
 string name;
 Node *next;
};
void append (Node *front, Node *newnode) {
 Node *n = front;
 if (n==NULL) return;
 while (n->next != NULL) n = n->next;
 n->next=newnode;
}


int main (int argc, char *argv[]) {
 int choice;
 int roll;
 string s;
 Node *front = NULL;
 Node *n;

 while (true) {
   cout << "choice? (0:create and append, 1:find 2:exit)" << endl;
   cin >> choice;
   switch (choice) {
    case 0: cout << "roll?"; cin >> roll; 
        cout <<"name?"; cin >> s;
        n = new Node(); 
        n->roll=roll; n->name=s;
        n->next=NULL;
        if(front==NULL) front = n;
        else append (front, n);
        break;
    case 1: cout << "roll?"; cin >> roll;
        n=front;
        if (n==NULL) break;
        while ((n->next != NULL)&&(n->roll!=roll)) n = n->next;
        if (n->roll==roll) cout << n->name << endl; 
        else cout << "not foundn";
        break;
    case 2: return 0;
    default: cout << "unrecognized choicen";
  }
 }
}

我不明白他们如何使用相同的结构"node"创建不同的条目。new node()做什么?也有人能解释一下这个函数是如何工作的吗?它如何在末尾添加新条目??

在c++中,结构体与类相同——除了默认的" public "访问权限。这种差异主要与发展偏好有关;大多数开发人员认为类是具有方法、成员和继承的对象,而结构只是将几个元素绑定在一起。

这段代码通过创建新的"节点"来创建新的条目。虽然它对每个节点使用相同的结构,但它将每个节点与列表中的下一个节点链接起来(通过"next"指针-它指向内存中的下一个节点)。

对于new node()部分,这只是分配内存(和一些其他的东西,但我假设因为您是c++的新手,您不想要无聊的细节!

也许你需要一个教程?试试这个!

这是一个链表。每个节点对象(new创建一个node结构的新实例,该实例随后是node类型的对象)。如果前面的节点没有更早的设置,则首先设置。这通常被称为链表的头。此后,每个新的"roll"值将被设置为一个新的实例并追加到列表中。

简单说明:

void append (Node *front, Node *newnode) {
 Node *n = front;  // assign front to a tempory Node pointer called n
 if (n==NULL) return;  // if n == NULL (points to nothing) then get out of here.
 while (n->next != NULL) n = n->next;  // loop through all node's starting from n, until n->next is NULL (points to nothing)
 n->next=newnode; // assign newnode to last n->next which is the end of the node tree
}