How to create vector of queues, and how do I add elements?
I want to be able to do the following:
-insert a new queue into the vector
-insert a new element into a queue
that's inside the vector.
:D
How to create vector of queues, and how do I add elements?
I want to be able to do the following:
-insert a new queue into the vector
-insert a new element into a queue
that's inside the vector.
:D
vector<queue<int>> vec; // vector of queues
vec.push_back(queue<int>()); // add a queue
vec[0].push(1); // push 1 into queue number 0.
You can do something like this:
int main( void )
{
typedef std::queue<int> Q;
std::vector<Q> v;
//Add a new queue to vector
v.push_back(Q());
//Add an element to the queue
v[0].push(1);
return 0;
}
typedef std::queue<int> IntQueue;
typedef std::vector<IntQueue> IntQueueVector
IntQueueVector myVector;
1)
myVector.push_back(IntQueue());
2)
myVector.back().push(1);
queue has the semantics that allow it to be used in std::vector, so you can just use it like any other vector when you come to add, eg use push_back to add a queue to the vector.
Inserting into a queue is with push() as you can only push into one end. You can access the queue through operator[] eg queuevec[i]
, where i is the number of the queue you wish to use.
If this is being used in a multi-threading context it is safe for two different threads to access two different queues within the vector without locking, but it is not safe for two threads to access the same queue. If you add a queue to the vector this may invalidate all the other queues in the vector during this period if they are being "moved", therefore you would need to lock your mutex to perform this action.