user1255410
user1255410

Reputation: 886

Push existing element of std::deque to the front?

I'm looking for a nice way to approach this problem. Not even sure if std::deque is what I want, but basically I need a container that I'll access front frequently and then move existing items to the front and add new ones to the front as well. Any way to do that with deque?

Upvotes: 3

Views: 3881

Answers (3)

KRoy
KRoy

Reputation: 1406

We can do it using deque. But can we do it using list as well ? (yes)

Push to front

std::deque<int> contents;

contents.push_front(1);
contents.push_front(2);
contents.push_front(3);

// Now has 3,2,1

lookup and move to front

// access 1 and move 1 to front
for(auto&& x:contents)
{
    if(1 == x)
    {
        contents.front.swap(x);
        break;
    }

}

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153810

For std::deque<T> you can access elements efficiently everywhere and you can efficiently add/remove elements at the front and at the end. However, std::deque<T> doesn't quite like to move objects from the middle: it will need to fill the gap in some form. Basically, moving an element would amount to a combination of an insert and an erase.

Using std::vector<T> or std::deque<T> may still be the best option when moving objects assuming neither the objects themselves nor the container is huge. For example, using a std::vector<T> of 1000 pointers and moving objects within is probably still faster than playing with a node-based container. At which sizes exactly the choices of containers change depends on your typical access pattern, the size of the object, etc.

For large objects or large containers you might want to use std::list<T> together with the splice() operation. ... and if all of these are too slow you might want to explain in more details what you are actually trying to and possibly use a different strategy and/or a more specialized containers like, e.g., a priority queue.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

You can use method push_front :).

Upvotes: 0

Related Questions