c++ - 结构在 C++ 中的行为方式

标签 c++ data-structures

当我被以下代码困住时,我正在阅读教程中的以下代码:

#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/

相关文章:

c++ - 从 C++ vector 中推送和检索值的意外输出

c++ - 在类名列表上迭代预处理器宏

c++ - 使用 BOOST_DLL_ALIAS 时了解并修复此错误消息

ios - 同步排队异步操作

algorithm - 关于使用什么方法/数据结构/算法的建议

C# 数据结构问题(使用哪个集合?)

c++ - 如何获得与Python中相同的系统时间?

java - 将二维数组传递给另一个类 : Java

c++ - 从队列中删除第一个元素?

c++ - 动态内存分配和内存块元数据