繁体   English   中英

如何构造可以替换typedef向量的类 <vector<T> &gt;类型

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

我正在学习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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM