C++ vector or Queue to build large Q in term of memory and speed
16,769
Solution 1
With std::vector
you can not efficiently simulate a queue - you may only PUSH and POP from one side of the container. If you need to implement a message queue then use a queue, that's what it's meant for.
Solution 2
There are many discussions regarding queue/vector/list on SO, you could search and reuse the resource. In short:
- Use
std::queue
: If you need fast insertion and deletion at both its beginning and its end; - Use
std::vector
, if you need random access to elements - When there are frequent insertions and deletions from the middle of
the sequence you need
std::list
As you use only push/pop to the container, std::queue
is the way instead of std::vector
for sure.
You can get more details from: http://en.cppreference.com/w/cpp/container
Author by
Shahzad
Updated on July 22, 2022Comments
-
Shahzad almost 2 years
I am building a large queue of messages and using only PUSH and POP so which will be more efficient (vector or Queue) to maintain a large data with maximum speed
struct MQStruct { wchar_t *serviceName; int durability; int msgType; int msgHeader; wchar_t *msgId; wchar_t *payload; int payloadSize; int ttl; int priority; }MQStructObj; vector<MQStruct> MQvector; queue<MQStruct> MSQ; int SendMessage(wchar_t *serviceName, int durability, int msgType, int msgHeader, wchar_t *msgId, wchar_t *payload, int payloadSize, int ttl, int priority) { MQStructObj.serviceName=serviceName; MQStructObj.durability=durability; MQStructObj.msgType=msgType; MQStructObj.msgHeader=msgHeader; MQStructObj.msgId=msgId; MQStructObj.payload=payload; MQStructObj.payloadSize=payloadSize; MQStructObj.ttl=ttl; MQStructObj.priority=priority; //Which one is better (Vector or Queue) in term of memory, speed and why MSQ.push(MQStructObj); //OR MQvector.push_back(MQStructObj); return 0; }
-
Gorpik over 11 yearsIn fact,
std::queue
(which uses anstd::deque
by default) is even better because it offers a more natural interface for OP's purposes and should have no performance penalty against a directstd::deque
. -
Shahzad over 11 yearsThank you so much for detail explanation, I don't need insertion and deletion on both ends so with ref to your ans, std::queue is better choice for me
-
billz over 11 years@Shahzad right. use std::queue instead, I'v updated my answer accordingly