《Essential C++ 中文版》Chapter4 課後題

4.1 / 4.2

stack.h文件ios

#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文件c++

#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;
}
相關文章
相關標籤/搜索