我想知道如何制作一个需要用户输入的字符串队列。例如,用户将输入一个词,然后该词进入队列。这是如何运作的?我现在只能排队一个整数。抱歉,我是初学者,我们的教授没有教我们任何东西:(
最佳答案
您可以使用默认的 STD 队列。查看此文档,Queue
std::queue
类是一个容器适配器,它为程序员提供了队列的功能,特别是 FIFO(先进先出)数据结构。
请注意,这与在您自己设计的队列中实现队列有很大不同class
例如典型的大学类(class)。
您只需要声明一个 std::queue
类型 std::string
, 例如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;
}
关于c++ - 如何使用用户输入制作字符串队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59013702/