Search code examples
c++move-semanticsdequeemplace

Emplace method in own deque


How can I write my own emplace method in my deque?

For example, I have this emplace_front function

template <typename ... Args>
void emplace_front(Args&& ...val) {
???
}

and Node constructor

template <typename ... Args>
Node(Args&&... val) : element(std::forward<Args>(val)...), next(nullptr),prev(nullptr) { }

I can't figure out how to write it correctly


Solution

  • If you have a continuous container, it looks something like:

    // first find/create free memory for your data, call it p
    new (p) T(std::forward<Args>(args)...);
    

    This is called 'placement new', and does not allocate, only construct
    p should be a T*


    If you have a node-based container, it looks something like:

    struct Node {
        Node *prev, *next;
        T value;
        template<typename... Args>
        Node(Args&&... args) : value(std::forward<Args>(args)...) {}
    };
    
    template<typename... Args>
    iterator emplace(Args&&... args) {
        Node* p = new Node(std::forward<Args>(args)...);
        // fill in p->next and p->prev here
        return {p};
    }
    

    you also need a constructor to your iterator that takes a Node*