Shahzad
Shahzad

Reputation: 305

C++ vector or Queue to build large Q in term of memory and speed

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;
}

Upvotes: 13

Views: 23937

Answers (2)

billz
billz

Reputation: 45410

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

Upvotes: 28

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 6

Related Questions