在C ++ 11中创建动态2D矩阵的好方法 [英] Nice way to create a dynamic 2D matrix in C++ 11

查看:73
本文介绍了在C ++ 11中创建动态2D矩阵的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何使用 new 创建动态2D矩阵并使用 delete 释放它。由于C ++ 11具有许多新的内存功能,例如 unique_ptr array 容器等;什么是创建2D矩阵的好方法,这样就不必使用 delete 运算符显式释放矩阵了?

I already know how to create a dynamic 2D matrix using new and free it using delete. Since C++ 11 is here with many new memory features such as unique_ptr, array container etc.; what is a nice way to create a 2D matrix so that one needs not to free the matrix explicitly using delete operator?

推荐答案

最简单的方法之一就是使用向量向量

One of the simplest ways is to use a vector of vectors

const int N = 10;
const int M = 10;
vector<vector<int>> matrix2d(N, vector<int>(M, 0)); // 10x10 zero-initialized matrix
matrix2d[0][0] = 42;

您当然可以使用单个向量并将其包装到访问器类中

You could of course use a single vector and wrap it into an accessor class

vector<int> matrix(N * M, 0) // Ditto as above, but needs stride-aware accessors

I

template <typename T>
class Matrix2D {
    std::vector<T> data;
    unsigned int sizeX, sizeY;
public:
    Matrix2D (unsigned int x, unsigned int y)
        : sizeX (x), sizeY (y) {
        data.resize (sizeX*sizeY);
    }

    T& operator()(unsigned int x, unsigned int y) {
        if (x >= sizeX || y>= sizeY)
            throw std::out_of_range("OOB access"); // Throw something more appropriate
        return data[sizeX*y + x]; // Stride-aware access
    }
};

在线示例

,或者将您的方式与智能指针。请注意,应谨慎使用 vector< vector< int>> 方法,因为矢量彼此独立,没有强制要求保持其大小固定的强制性

or perhaps combine your way with a smart pointer. Notice that the vector<vector<int>> approach should be used with caution since the vectors are independent from each other and there's nothing to enforce that they should keep their size fixed.

这篇关于在C ++ 11中创建动态2D矩阵的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆