如何在C ++中访问和修改std :: queue中的元素

时间:2013-04-28 14:42:53

标签: c++ queue

正如标题中所述,我如何访问队列中多个结构成员而不将其从队列中删除?我只想更改结构中int的值,但我需要将它们保留在队列中供以后使用。

3 个答案:

答案 0 :(得分:2)

您可以将std::deque用于此目的。使用下标运算符无法使用std:queue随机访问:

http://www.cplusplus.com/reference/deque/deque/

答案 1 :(得分:0)

您可以使用迭代器,搜索需要修改的元素,检索迭代器并更改值。使用std :: deque进行此类操作。

答案 2 :(得分:0)

std::queue是一个C ++标准库容器适配器,设计用作FIFO抽象数据结构,即它不允许您访问其中的元素:它只允许您将push元素放入开头,将pop放在最后。

如果要访问内部元素以进行读取或修改,则应选择其他数据结构。选择将取决于最常使用它执行的操作。如果您在没有明确指定容器的情况下使用std::queue(最有可能),它在幕后使用std::deque容器,因此您可以直接使用它:它甚至可以让您访问其中的元素使用索引,即

std::deque<SomeStruct> data;

data.push_back(x); // instead of queue.push(...);
data.pop_front(); // instead of queue.pop();

data[i]; // to access elements inside the queue. Note that indexing start from the beginning of the structure, i.e. data[0] is the next element to be pop'ed, not the last push'ed.