Cplusplus的模板类

概述

  1. 模板类(class template) 是 C++ 提供的 泛型编程工具,允许你定义一个类,但类中的成员类型可以在实例化时指定。这样就能避免为不同类型重复写相似的类.

定义

#include <iostream>
#include <vector>
#include <stdexcept>

// 定义模板类
template <typename T>
class Stack {
private:
    std::vector<T> elements;  // 用 vector 存储栈元素

public:
    // 压栈
    void push(const T& item) {
        elements.push_back(item);
    }

    // 出栈
    void pop() {
        if (elements.empty()) {
            throw std::out_of_range("Stack<>::pop(): empty stack");
        }
        elements.pop_back();
    }

    // 获取栈顶元素
    T top() const {
        if (elements.empty()) {
            throw std::out_of_range("Stack<>::top(): empty stack");
        }
        return elements.back();
    }

    // 判断栈是否为空
    bool empty() const {
        return elements.empty();
    }

    // 获取栈大小
    size_t size() const {
        return elements.size();
    }
};

// 测试代码
int main() {
    try {
        Stack<int> intStack;       // int 类型的栈
        Stack<std::string> strStack; // string 类型的栈

        intStack.push(1);
        intStack.push(2);
        intStack.push(3);

        std::cout << "intStack top: " << intStack.top() << std::endl;
        intStack.pop();
        std::cout << "intStack top after pop: " << intStack.top() << std::endl;

        strStack.push("Hello");
        strStack.push("World");

        std::cout << "strStack top: " << strStack.top() << std::endl;
        strStack.pop();
        std::cout << "strStack top after pop: " << strStack.top() << std::endl;

    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}