Search code examples
c++stldeque

How to extract an element from a deque?


Given the following code:

void World::extractStates(deque<string> myDeque)
{
    unsigned int i = 0;
    string current; // current extracted string

    while (i < myDeque.size())      // run on the entire vector and extract all the elements
    {
        current =  myDeque.pop_front(); // doesn't work 
        // do more stuff
    }
}

I want to extract each iteration the element at the front, but pop_front() is a void method. How can I get the element (at the front) then?


Solution

  • Use front to read the item and pop_front to remove it.

    current = myDeque.front();
    myDeque.pop_front();
    

    This way of doing things may seem counter-productive, but it is necessary in order for deque to provide adequate exception-safety guarantees.