(原創) 使用std::vector模拟std::stack? (C/C++) (STL)
实务上并不会用std::vector去模拟std::stack,这是我修C++在Lab上的一个练习,要我们用std::vector去模拟std::stack,还蛮有趣的。
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : UseVectorSimulateStack.cpp
5
Compiler : Visual C++ 8.0
6
Description : Demo how to use std::vector to simulte std::stack
7
Release : 11/15/2006
8
*/
9
#include <iostream>
10
#include <vector>
11
12
class StackInt {
13
public:
14
size_t size();
15
bool empty();
16
int top();
17
void push(int value);
18
void pop();
19
private:
20
std::vector<int> stack;
21
};
22
23
size_t StackInt::size() {
24
return this->stack.size();
25
}
26
27
bool StackInt::empty() {
28
return stack.empty();
29
}
30
31
int StackInt::top() {
32
// vector.end() is the one past the end,
33
// so we have to --
34
return *--stack.end();
35
}
36
37
void StackInt::push(int value) {
38
std::cout << "Push " << value << std::endl;
39
stack.push_back(value);
40
}
41
42
void StackInt::pop() {
43
std::cout << "Pop " << this->top() << std::endl;
44
stack.pop_back();
45
}
46
47
int main() {
48
const int stk_size = 10;
49
StackInt intStack;
50
51
int ix = 0;
52
while(intStack.size() != stk_size) {
53
intStack.push(ix++);
54
}
55
56
int error_cnt = 0;
57
58
while(intStack.empty() == false) {
59
int value = intStack.top();
60
61
std::cout << "the value of the top element is " << value << std::endl;
62
intStack.pop();
63
}
64
65
return 0;
66
}
67
68
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : UseVectorSimulateStack.cpp5
Compiler : Visual C++ 8.06
Description : Demo how to use std::vector to simulte std::stack7
Release : 11/15/20068
*/9
#include <iostream>10
#include <vector>11

12
class StackInt {13
public:14
size_t size();15
bool empty();16
int top();17
void push(int value);18
void pop();19
private:20
std::vector<int> stack;21
};22

23
size_t StackInt::size() {24
return this->stack.size();25
}26

27
bool StackInt::empty() {28
return stack.empty();29
}30

31
int StackInt::top() {32
// vector.end() is the one past the end,33
// so we have to --34
return *--stack.end();35
}36

37
void StackInt::push(int value) {38
std::cout << "Push " << value << std::endl;39
stack.push_back(value);40
}41

42
void StackInt::pop() {43
std::cout << "Pop " << this->top() << std::endl;44
stack.pop_back();45
}46

47
int main() {48
const int stk_size = 10;49
StackInt intStack;50

51
int ix = 0;52
while(intStack.size() != stk_size) {53
intStack.push(ix++);54
}55

56
int error_cnt = 0;57

58
while(intStack.empty() == false) {59
int value = intStack.top();60

61
std::cout << "the value of the top element is " << value << std::endl;62
intStack.pop();63
}64

65
return 0;66
}67

68



浙公网安备 33010602011771号