简体   繁体   中英

How to access and modify an element inside std::queue in C++

As it says in title, how can I access multiple members of a structure in a queue without getting them out of the queue? I just want to change the value of an int in the structure but I need to keep them in queue for later use.

You can use std::deque for this purpose. It is not possible to access randomly with std:queue using subscript operator:

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

You can use iterator, serarch the element you need to modify, retrive the iterator and cnange the value. Use std::deque for this kind of operations.

The std::queue is a C++ Standard Library container adapter designed to operate as a FIFO abstract data structure, ie it doesn't allow you to access elements inside it: it only allows you to push elements into the beginning and pop them off the end.

If you want the access to inner elements for reading or modification, you should choose a different data structure. The selection will depend on the operations most often performed with it. If you used std::queue without explicitly specifying the container (most probably), it used the std::deque container behind the scenes, so you can just use it directly: it will even allow you to access the elements inside it using indexing, ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM