队列中的项目不断重置。在主菜单中选择显示功能后,如何显示队列中的所有项目?如果我在使用"添加项目"之后选择了显示功能。功能,它不会显示我放置的项目。在主菜单中选择显示功能后,如何显示队列中的所有项目?
#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;
}
}
答案 0 :(得分:0)
问题在于对mainMenu()函数的递归调用。如在
if (ch == 'N')
{
mainMenu();
}
每次进入mainMenu()函数时,都会在函数堆栈上创建一个新队列,因此它不会包含先前函数调用的元素。您可能希望在main()函数(或其他地方)中初始化队列,然后将其作为参数传递给mainMenu()函数。
答案 1 :(得分:0)
问题在于对mainMenu()函数的递归调用,因为哪个队列一次又一次地被初始化。为避免这种情况,您可以将num初始化为num=0
,之后在mainmenu()中使用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;
}
}
}