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
CodePudding user response:
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*
CodePudding user response:
"Emplace" simply means to construct the object once and not move it (although, depending on the specifics of the container, a future operation on the container might move existing elements).
Your deque appears to be built out of nodes and pointers. In this kind of container, emplacement is easy. Just create a node (that holds an element constructed from the forward arguments) and then don't move it. Rearrange the pointers in order to insert the node into the data structure. For example, it might look something like this:
template <typename ... Args>
void emplace_front(Args&& ...val) {
auto* node = new Node(std::forward<Args>(val)...);
node->prev = head_; // assuming it is circularly linked
head_->next = node;
node->next = front_;
front_->prev = node;
front_ = node;
size_ ;
}