2

正如它在标题中所说,如何访问队列中结构的多个成员而不将它们从队列中取出?我只想更改int结构中 an 的值,但我需要将它们保留在队列中以备后用。

4

3 回答 3

3

您可以std::deque用于此目的。使用下标运算符使用 std:queue 随机访问是不可能的:

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

于 2013-04-28T14:46:58.420 回答
1

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.
于 2013-04-28T15:17:20.213 回答
0

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

于 2013-04-28T14:52:31.790 回答