c++ - 简单,但找不到 : syntax to work with member variables of STL queues with type class

标签 c++ class stl queue

这道题是作业帮助;我没有看到任何违反规则的地方。

这是我的功能:

void display_queue(queue<cat> original_queue) 
{                       
  int dummy_integer;
  queue<cat> dummy_queue;       
  cout << endl << "The queue contains: " << endl;

  //reads out the first q while moving values to second q
  while (!original_queue.empty())
  {
    cout << ' ' << original_queue.front().ears;
    dummy_integer = original_queue.front().ears;
    original_queue.pop();
    dummy_queue.push(dummy_integer).ears;
  }

  //put the values from q2 back to q1
  while (!dummy_queue.empty())
  {
    dummy_integer = dummy_queue.front().ears;
    dummy_queue.pop();
    original_queue.push(dummy_integer).ears;
  }

}

这是我更大的程序中一个函数的精简、重命名模型,它模拟内核的进程管理方面。虽然当它是队列时我可以成功显示队列的内容,但当它是那些尖括号中的类时我还没有遇到语法。

我在尝试 .push 的行中出现了我不正确的语法,我觉得我已经尝试了所有可能的选项,但显然这是错误的,我只是在胡闹。

有谁知 Prop 体怎么写吗?

最佳答案

假设你有一个构造函数cat::cat(int),你可以添加一个新的cat对象到队列中:

dummy_queue.push(cat(dummy_integer));

但是,更大的问题是您是否需要进行所有这些项目洗牌。 STL queue 模板有一个人为的限制,即不公开迭代其项目的方法。考虑改用 deque,这样您就可以遍历队列,而不必删除并重新插入其内容。

void display_queue(const deque<cat> &queue) 
{
    cout << endl << "The queue contains: " << endl;

    while (deque<cat>::const_iterator cat = queue.begin(); cat != queue.end(); ++cat)
    {
        cout << ' ' << cat->ears;
    }
}

或者,您至少可以通过简单地迭代原始队列的拷贝来稍微简化您的代码。如果您销毁了原始队列的拷贝,则无需恢复原始队列。

这也可以让您进行很好的优化并将参数更改为 const queue &。这会将来自调用者的原始队列作为引用传递,而不是复制它。

void display_queue(const queue<cat> &original_queue) 
{
    queue<cat> queue_copy(original_queue);       
    cout << endl << "The queue contains: " << endl;

    while (!queue_copy.empty())
    {
        cout << ' ' << queue_copy.front().ears;
        queue_copy.pop();
    }
}

关于c++ - 简单,但找不到 : syntax to work with member variables of STL queues with type class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335658/

相关文章:

c++ - Typedef struct C 目标到 C++

c++ - 在中间访问 std::list

c++ - 如何对 std :list when you need member data? 进行排序

java - 我可以在不使用类名的情况下调用另一个类的静态方法吗?

C# - 从第三方库导入类并使其成为派生类(或类似的类)

c++ - 最有可能使用什么方法来处理多个键以使用 STL 容器获取值?

c++ - 更改迭代器比较时 vector 迭代器不可取消引用

c++ - QPolarChart隐藏径向刻度标签

c++ - C 与 C++ 对象的静态初始化

c++ - 浮点运算的最佳实践