当我被以下代码困住时,我正在阅读教程中的以下代码:
#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 found\n";
break;
case 2: return 0;
default: cout << "unrecognized choice\n";
}
}
}
我不明白他们如何使用相同的结构“节点”创建不同的条目。
还有 new node()
是做什么的?
也有人可以解释一下函数 append 是如何工作的吗?它如何在末尾附加新条目??
最佳答案
在 C++ 中,结构与类相同 - 除了默认的“公共(public)”访问权限。差异主要与发展偏好有关。大多数开发人员将类视为具有方法、成员和继承的对象,而结构只是将几个元素绑定(bind)在一起。
此代码通过创建新“节点”来创建新条目。 Whist 它对每个节点使用相同的结构,它将每个节点与列表中的下一个节点链接起来(通过“下一个”指针 - 它指向内存中的下一个节点)。
至于 new node()
部分,这只是分配内存(以及其他一些东西,但我假设因为您是 C++ 的新手,所以您不希望无聊的详情!
也许您需要教程?尝试 this !
关于c++ - 结构在 C++ 中的行为方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5619821/