【问题标题】:How to make a queue of strings using user input?如何使用用户输入制作字符串队列?
【发布时间】:2019-11-24 00:46:34
【问题描述】:

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

【问题讨论】:

  • 如果您提供教授为整数队列显示的代码,可能会对想要回答您的问题的人有所帮助
  • std::queue<std::string>
  • 我很确定提问者任务的目的是自己实现一个队列。

标签: c++ queue


【解决方案1】:

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

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

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

您只需要声明一个std::string 类型的std::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;
}

【讨论】:

  • 正如@Raymond 所说,std::queue 与用户定义的queue 完全不同,因为它在其定义中使用模板(这意味着您可以拥有任何类型的std::queue , 而“college”定义通常只为一种类型声明,例如int)。如果您想了解更多关于实现自己的队列的信息,那么您一定要查看GeekForGeeks article about queues。读完之后,您将了解队列数据结构,并且更有可能了解新的结构。
  • @whiskeyo 是正确的,但是对于用户实现的队列,队列实现的结构/类也仍然可以使用模板化变量,以防万一它通常不在他所说的单个变量中,如int。我不知道这是否与 OP 的问题有关。但也想感谢您的精彩评论。
猜你喜欢
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
相关资源
最近更新 更多