c++中的结构是如何工作的
how do structures behave in c++
我正在阅读下面的教程代码,当我被下面的代码卡住时:
#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
}
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- sdl软件渲染器不工作,工作在硬件加速的一个