栈模板

Gavin

支持随机访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <vector>
#include <stdexcept>

template <typename T>
class Stack {
private:
std::vector<T> container;

public:
void push(const T& value) {
container.push_back(value);
}

void push(T&& value) {
container.push_back(std::move(value));
}

template <typename... Args>
void emplace(Args&&... args) {
container.emplace_back(std::forward<Args>(args)...);
}

void pop() {
if (empty()) {
throw std::out_of_range("Cannot pop from an empty stack");
}
container.pop_back();
}

T& top() {
if (empty()) {
throw std::out_of_range("Stack is empty");
}
return container.back();
}

const T& top() const {
if (empty()) {
throw std::out_of_range("Stack is empty");
}
return container.back();
}

bool empty() const {
return container.empty();
}

size_t size() const {
return container.size();
}

void clear() {
container.clear();
}

T& operator[](size_t index) {
return container[index];
}

const T& operator[](size_t index) const {
return container[index];
}

T& at(size_t index) {
return container.at(index);
}

const T& at(size_t index) const {
return container.at(index);
}

T& peek_down(size_t depth) {
if (depth >= container.size()) {
throw std::out_of_range("Peek depth out of range");
}
return container[container.size() - 1 - depth];
}

const T& peek_down(size_t depth) const {
if (depth >= container.size()) {
throw std::out_of_range("Peek depth out of range");
}
return container[container.size() - 1 - depth];
}

using iterator = typename std::vector<T>::iterator;
using const_iterator = typename std::vector<T>::const_iterator;

iterator begin() { return container.begin(); }
iterator end() { return container.end(); }
const_iterator begin() const { return container.begin(); }
const_iterator end() const { return container.end(); }

using reverse_iterator = typename std::vector<T>::reverse_iterator;
using const_reverse_iterator = typename std::vector<T>::const_reverse_iterator;

reverse_iterator rbegin() { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
const_reverse_iterator rend() const { return container.rend(); }
};
  • 标题: 栈模板
  • 作者: Gavin
  • 创建于 : 2026-04-16 08:53:00
  • 更新于 : 2026-04-16 08:53:00
  • 链接: https://gavin-blog.pages.dev/2026/栈模板/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
目录
栈模板