2

I have a queue. If it exceeds X size, when I push an element I want to remove the first element of the queue. (the last element that would get popped and the first element pushed in)

void ClientPlayerManager::queueTableMessage( const std::string& playerName, const std::string& message )
{
    m_tableQ.push(std::make_pair(playerName,message));

    if(m_tableQ.size() > m_maxTableMessages)
    {
        //m_tableQ.pop_back(); does not exist
    }
}

Is there a way to do this with a std queue?

Thanks

2
  • In a FIFO queue, the last element that would get popped is at the opposite end from the first element pushed in. Which do you want? Commented May 29, 2012 at 19:20
  • Yes, it's quite confusing. Why not just use push and pop and forget about it? Commented May 29, 2012 at 19:21

2 Answers 2

6

You can use a std::deque instead of a std::queue, which supports push_front, push_back, pop_front, and pop_back. This also allows for random access throughout, but you can just ignore that and treat the deque like a double-ended queue. (In fact, deque is short for double-ended queue).

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to remove an element from the opposite end from what pop does, just skip pushing it in the first place:

if(m_tableQ.size() < m_maxTableMessages) {
    m_tableQ.push(std::make_pair(playerName,message));
}

2 Comments

No, the idea is that I want the top X messages to stay, when I have X messages, the one of least importance (the oldest one) goes and a new one is in.
@Milo: In that case, you can just use pop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.