gpt4 book ai didi

c++ - 如何在不同的功能中使用队列?

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

队列中的项目不断重置。在主菜单中选择“显示”功能后,如何显示队列中的所有项目?如果我在使用“添加项目”功能放置项目后选择显示功能,则不会显示我放置的项目。在主菜单中选择“显示”功能后,如何显示队列中的所有项目?

#include <iostream>
#include "linkedQueue.h"

using namespace std;

void mainMenu();
void addQueues();
void Display();

int main()
{
mainMenu();
system("pause>0");
return 0;
}

void mainMenu()
{
system("cls");
int num;
linkedQueueType<int> queue;
cout << "\t\t\t OPERATIONS";
cout << "\n\n [1] Add items";
cout << "\n [2] Delete items";
cout << "\n [3] Show the number of items";
cout << "\n [4] Show min and max items";
cout << "\n [5] Find an item";
cout << "\n [6] Sort items";
cout << "\n [7] Print all items";
cout << "\n [8] Exit";

cout << " \n\n Enter choice: ";
cin >> num;
switch (num)
{
case 1:

int x;
char ch;
cout << "\nAdd number: ";
cin >> x;
queue.addQueue(x);
cout << "Enter again? (Y/N) ";
cin >> ch;
while (ch == 'Y')
{
cout << "\nAdd number: ";
cin >> x;
queue.addQueue(x);
cout << "Enter again? (Y/N) ";
cin >> ch;
}
if (ch == 'N')
{
mainMenu();
}
break;

case 7:

cout << "Queue Elements: ";

if (queue.isEmptyQueue())
cout << "Queue is empty - add item first\n";
else
{
while (!queue.isEmptyQueue())
{
cout << queue.front() << " ";
queue.deleteQueue();
}
}

break;

default:
cout << "Invalid" << endl;
}
}

最佳答案

问题在于对 mainMenu() 函数的递归调用,因为队列被一次又一次地初始化。为了避免这种情况,您可以将 num 初始化为 0 作为 num=0 ,然后在 mainmenu() 中使用 while 循环并将代码放入 while 循环中

#include <iostream>
#include "linkedQueue.h"
using namespace std;
void mainMenu();
void addQueues();
void Display();

int main()
{
mainMenu();
system("pause>0");
return 0;
}

void mainMenu()
{
system("cls");
int num=0;
linkedQueueType<int> queue;
while(num!=8)
{
cout << "\t\t\t OPERATIONS";
cout << "\n\n [1] Add items";
cout << "\n [2] Delete items";
cout << "\n [3] Show the number of items";
cout << "\n [4] Show min and max items";
cout << "\n [5] Find an item";
cout << "\n [6] Sort items";
cout << "\n [7] Print all items";
cout << "\n [8] Exit";

cout << " \n\n Enter choice: ";
cin >> num;
switch (num)
{
case 1:

int x;
char ch;
cout << "\nAdd number: ";
cin >> x;
queue.addQueue(x);
cout << "Enter again? (Y/N) ";
cin >> ch;
while (ch == 'Y')
{
cout << "\nAdd number: ";
cin >> x;
queue.addQueue(x);
cout << "Enter again? (Y/N) ";
cin >> ch;
}
break;

case 7:

cout << "Queue Elements: ";

if (queue.isEmptyQueue())
cout << "Queue is empty - add item first\n";
else
{
while (!queue.isEmptyQueue())
{
cout << queue.front() << " ";
queue.deleteQueue();
}
}

break;

default:
cout << "Invalid" << endl;
}
}
}

关于c++ - 如何在不同的功能中使用队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223910/

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