如何使用用户输入创建字符串队列?



我想知道如何制作需要用户输入的字符串队列。例如,用户将输入一个单词,然后该单词进入队列。这是怎么回事?我现在只能排队一个整数。对不起,我是初学者,我们的教授没有教我们任何东西:(

您可以使用默认的 STD 队列。查看此文档,队列

std::queue类是一个容器适配器,它为程序员提供队列的功能,特别是 FIFO(先进先出(数据结构。

请注意,这与在您自己的设计class(例如典型的大学课程(中实现队列非常不同。

您只需要声明一个类型std::stringstd::queue,例如std::queue<std::string> q.

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <ostream>
#include <istream>
int main ()
{
// Declare your queue of type std::string
std::queue<std::string> q;
// Push 1 to 3
q.push ("1");
q.push ("2");
q.push ("3");
// Declare a string variable
std::string input;
// Prompt
std::cout << "- Please input a string: " << std::endl;
// Catch user input and store
std::cin >> input;
// Push value inputted by the user
q.push(input);
// Loop while the queue is not empty, while popping each value
while (not q.empty ())
{
// Output front of the queue
std::cout << q.front () << std::endl;
// Pop the queue, delete item
q.pop ();
}
// New line, formatting purposes
std::cout << std::endl;
return 0;
}

最新更新