一个完整的泛型组件

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)一个泛型容器 + 一个泛型算法:

#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

/* 一个泛型容器:装什么都行,但"求和"只对数字开放 */
template <typename T>
class Bag {
public:
    void add(const T &v) { data_.push_back(v); }
    int size() const { return static_cast<int>(data_.size()); }
    const T &at(int i) const { return data_[static_cast<std::size_t>(i)]; }

    /* 这一句把"哪些类型能求和"这条线划在了编译期 */
    T sum() const {
        static_assert(std::is_arithmetic_v<T>, "sum 只对数字开放");
        T s = T();
        for (const T &x : data_) s = s + x;
        return s;
    }
private:
    std::vector<T> data_;
};

/* 一个泛型算法:只要求"能走一遍、能和 line 比大小" */
template <typename It, typename T>
int count_above(It first, It last, const T &line) {
    int n = 0;
    for (It it = first; it != last; ++it) if (*it > line) n++;
    return n;
}

int main() {
    Bag<int> bi;
    bi.add(5); bi.add(3); bi.add(9);

    Bag<std::string> bs;
    bs.add("apple"); bs.add("pear");

    std::vector<int> v{5, 3, 9};

    std::cout << bi.size() << "/" << bi.sum() << "/"
              << bs.size() << "/" << bs.at(1) << "/"
              << count_above(v.begin(), v.end(), 4) << "\n";
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论