JAN
JAN

Reputation: 21885

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?

Upvotes: 3

Views: 2492

Answers (1)

Jon
Jon

Reputation: 437684

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.

Upvotes: 15

Related Questions