4.1 / 4.2
stack.h
文件
#pragma once
#include<string>
#include<vector>
class Stack {
public:
bool push(const std::string &); // 参数名可以省略
bool pop(std::string &);
bool peek(std::string &);
bool empty() {
return _stack.size() == 0;
}
bool full() {
// 实际上max_size不一定代表元素个数一定能达到这个值
return _stack.size() == _stack.max_size();
}
// 如果定义在class本身中, 那么默认为inline函数
int size() {
return _stack.size();
}
bool find(const std::string &);
int count(const std::string &);
private:
std::vector<std::string> _stack;
};
stack.cc
文件
#include<iostream>
#include "stack.h"
bool Stack::push(const std::string & ele) {
if (full()) {
return false;
}
_stack.push_back(ele);
return true;
}
bool Stack::peek(std::string & ele) {
if (empty()) {
return false;
}
ele = _stack.back();
return true;
}
bool Stack::pop(std::string & ele) {
if (empty()) {
return false;
}
ele = _stack.back();
_stack.pop_back();
return true;
}
bool Stack::find(const std::string & ele) {
if (empty()) {
return false;
}
std::vector<std::string>::iterator it = std::find(_stack.begin(), _stack.end(), ele);
return it != _stack.end();
}
int Stack::count(const std::string & ele) {
int cnt = 0;
if (empty()) {
return cnt;
}
auto it = _stack.begin();
while (true) {
it = std::find(it, _stack.end(), ele);
if (it != _stack.end()) {
cnt++;
it++; // 这里一定要++, 不然会一直循环
} else {
break;
}
}
return cnt;
}
int main() {
Stack stack;
stack.push("Hello");
stack.push(" ");
stack.push("World");
stack.push("Hello");
std::cout << "Find Hello : " << stack.find("Hello") << std::endl;
std::cout << "How many times about Hello :" << stack.count("Hello") << std::endl;
while (!stack.empty()) {
std::string str;
stack.pop(str);
std::cout << str << std::endl;
}
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。