C++でスタックを書いてみた
スタックが必要になったので書いてみた.
#include <iostream> #include <cstdlib> const int STACK_SIZE = 80; class MyStack { private: int count; int data[STACK_SIZE]; public: MyStack(); //~MyStack(); void push(const int item); int pop(); }; MyStack::MyStack() { count = 0; } void MyStack::push(const int item) { data[count] = item; count++; } int MyStack::pop() { count--; return data[count]; } int main() { MyStack myStack; myStack.push(1); myStack.push(2); myStack.push(3); std::cout << myStack.pop() << std::endl; std::cout << myStack.pop() << std::endl; std::cout << myStack.pop() << std::endl; return 0; }
本来ならpushとpopに範囲チェックが必要.assert();がスマートかif ... return -1;がスマートかいま迷ってます.