关于c++:Essential-C-中文版Chapter4-课后题

6次阅读

共计 1456 个字符,预计需要花费 4 分钟才能阅读完成。

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;
}
正文完
 0