为了练习,我实现了像Queue这样的简单STL。
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <stdexcept>
template <typename T>
class queue {
public:
~queue();
bool empty() const;
size_t size() const;
T const& front() const;
T& front();
void push(T const& data);
void push(T&& data);
//void emplace (T&&... args);
// void swap (queue& x);
void pop();
private:
size_t elements = 0;
struct node {
T data;
node *next;
node(T const& data, node* next)
: data(data)
, next(next) {
}
node(T&& data, node* next)
: data(std::move(data))
, next(next) {
}
};
node *head = nullptr;
node *tail = nullptr;
};
template <typename T>
queue<T>::~queue() {
node *curr;
while(head) {
curr = head;
head = head->next;
delete curr;
}
}
template <typename T>
bool queue<T>::empty() const {
return elements == 0;
// return head == nullptr;
}
template <typename T>
size_t queue<T>::size() const {
return elements;
}
template <typename T>
T const& queue<T>::front() const {
if(head == nullptr)
throw std::runtime_error("Invalid Action");
return head->data;
}
template <typename T>
T& queue<T>::front() {
if(head == nullptr)
throw std::runtime_error("Invalid Action");
return head->data;
}
template <typename T>
void queue<T>::push(T const& data) {
node *newNode = new node(data, nullptr);
if(head == nullptr) head = newNode;
else tail->next = newNode;
tail = newNode;
++elements;
}
template <typename T>
void queue<T>::push(T&& data) {
node *newNode = new node(std::move(data), nullptr);
if(head == nullptr) head = newNode;
else tail->next = newNode;
tail = newNode;
++elements;
}
template <typename T>
void queue<T>::pop() {
if(head == nullptr)
throw std::runtime_error("Invalid Action");
node* remove = head;
head = head->next;
delete remove;
--elements;
}
#endif // QUEUE_H
一切都很好。您能否给我一些见解如何有效地实现C ++ 11 emplace(Args&&... args)
和swap(queue& x)
?完整的代码将不胜感激,但一些想法就足够了。
提前致谢!
答案 0 :(得分:3)
swap(queue&)
只需交换队列中的每个成员:
template <typename T>
void queue<T>::swap (queue<T>& rhs)
{
std::swap(elements, rhs.elements);
std::swap(head, rhs.head);
std::swap(tail, rhs.tail);
}
对于emplace(Args&&... args)
,您必须添加一个节点构造函数,以便从T
构建Args
类似的东西:
struct node {
T data;
node *next;
template <typename ... Ts>
node(node* next, Ts&&...args) :
data(std::forward<Ts>(args)...),
next(next)
{}
};
template <typename T>
template <typename... Ts>
void queue<T>::emplace(Ts&&... args)
{
node *newNode = new node(nullptr, std::forward<Ts>(args)...);
if (head == nullptr) head = newNode;
else tail->next = newNode;
tail = newNode;
++elements;
}