如何构造可以替换typedef vector<vector> Type 的类<T>

How to construct class that can replace typedef vector<vector<T>> Type

本文关键字:lt gt vector Type 的类 何构造 替换 typedef      更新时间:2023-10-16

我正在学习C++的课程,并希望构建自己的课程,而不是使用2D向量" typedef vector<vector<T>> C_type "。我写了一些代码:

class T {
    public:
    int a;
    int b;
    T(int a, int b) : a(a), b(b){}
};

现在我有:

typedef vector<vector<T>> C_type;

我想改用一个类并创建一个构造函数并初始化它,如下所示:

class C_type {
vector<vector<T>> name;
C_type();}
C_type::C_type(){name = vector<vector<T>>(..........

我想使用 2D 矢量作为类成员。谢谢。

这里有一些简单的开始:

#include <iostream>
#include <vector>
template<typename T>
class C_type {
public:
    C_type(int rows, int cols) : _vec(std::vector<std::vector<T>>(rows, std::vector<T>(cols))) {}
    C_type() : C_type(0, 0) {}
    T get(int row, int col) { return this->_vec.at(row).at(col); }
    void set(int row, int col, T value) { this->_vec.at(row).at(col) = value; }
    size_t rows() { return this->_vec.size(); }
    size_t cols() { return this->_vec.front().size(); }
private:
    std::vector<std::vector<T>> _vec;
};
int main() {
    C_type<int> c(2, 2);
    for ( unsigned i = 0; i < c.rows(); ++i ) {
        for ( unsigned j = 0; j < c.cols(); ++j ) {
            c.set(i, j, i + j);
        }   
    }
    for ( unsigned i = 0; i < c.rows(); ++i ) {
        for ( unsigned j = 0; j < c.cols(); ++j ) {
            std::cout << c.get(i, j) << " ";
        }   
        std::cout << "n";
    }
    return 0;
}