(原創) 使用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
 4Filename    : UseVectorSimulateStack.cpp
 5Compiler    : Visual C++ 8.0
 6Description : Demo how to use std::vector to simulte std::stack
 7Release     : 11/15/2006
 8*/

 9#include <iostream>
10#include <vector>
11
12class StackInt {
13public:
14  size_t size();
15  bool empty();
16  int  top();
17  void push(int value);
18  void pop();
19private:
20  std::vector<int> stack;
21}
;
22
23size_t StackInt::size() {
24  return this->stack.size();
25}

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

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

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

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

46
47int 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

posted on 2006-11-15 16:36  真 OO无双  阅读(1689)  评论(0编辑  收藏  举报

导航