gpt4 book ai didi

c++ - 放弃检查列表是否为空

转载 作者:行者123 更新时间:2023-11-30 03:55:48 25 4
gpt4 key购买 nike

由于您上次设法修复了我的代码,所以我想再次寻求您的帮助。

因为我已经有了一个包含五个元素的预定义列表,所以这段代码看起来很无意义,因为没有检查列表是否为空的目的。我似乎无法弄清楚谁可以绕过 if-else,只保留“插入”功能而不是检查列表是否为空...

#include <iostream>
#include <cmath>

using namespace std;

struct node
{
string nameOfFood;
int eatCalories;
int number;
node *next;

};

bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&last, string name, int eatCalories);
void insert(node *&head, node *&last, string name, int eatCalories);
void showList(node *current);


bool isEmpty(node *head)
{
if(head == NULL)
return true;
else
return false;
}

char menu()
{
char choice;

cout << "Menu\n";
cout << "1. Add food, beverage etc.\n";
cout << "2. Show the list of food(s), beverage(s) etc.\n";
cout << "3. Update your current weight\n";
cout << "4. What have you been eaten?\n";
cout << "5. What exercise have you done?\n";
cout << "6. Exit program \n";

cin >> choice;

return choice;

}

void insertAsFirstElement(node *&head, node *&last, string nameOfFood, int eatCalories)
{
node *temp = new node;
temp->nameOfFood = nameOfFood;
temp->eatCalories = eatCalories;
temp->next = NULL;
head = temp;
last = temp;
}

void insert(node *&head, node *&last, string nameOfFood, int eatCalories)
{
if(isEmpty(head))
insertAsFirstElement(head, last, nameOfFood, eatCalories);
else
{
node *temp = new node;
temp->nameOfFood = nameOfFood;
temp->eatCalories = eatCalories;
temp->next = NULL;
last->next = temp;
last = temp;
}

}

如果您需要更多代码,请告诉我?

希望得到您的帮助!

最佳答案

该检查是必要的,因为如果您的列表为空,那么您必须执行一定数量的操作,这些操作仅在这种情况下执行。

实现自己的链表真的没有任何意义。标准已经定义了比你的更灵活的类,参见 std::forward_list (单链表)和 std::list (双向链表) .

建议您在选择容器时默认使用std::vectorstd::array。在这种情况下,如果您只有 5 个元素的列表,只需使用 std::array 和自定义类型:

struct food
{
string nameOfFood;
int eatCalories;
int number;
};

然后:

std::array<food, 5> food_list { ... };

关于c++ - 放弃检查列表是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28886782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com