用方括号运算符实现矩阵类的安全方法 [英] Safe way to implement matrix class with bracket operators

查看:93
本文介绍了用方括号运算符实现矩阵类的安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此,我正在编写一个二维矩阵类,包装了向量的向量.

I am writing a bidimensional matrix class just for the sake of it, wrapping a vector of vectors.

由于矩阵必须具有正维,所以我确保矩阵不会构造错误,从那时起,我假定矩阵至少包含一个元素:

Since matrices must have positive dimensions I make sure the matrix cannot be ill-constructed, and from then on I assume the matrix has at least one element:

Matrix2D::Matrix2D(size_t rows, size_t cols)
{
    if (rows == 0 || cols == 0)
    {
        throw std::invalid_argument("Matrix cannot have zero as dimension");
    }
    ...

我想为用户提供一种使用串联的[](即m[1][1])访问和修改特定元素的方法.但是,我不希望用户能够修改矩阵的尺寸或修改一行中的列数.我目前提供像下面这样的重载operator[]的方法是不够的,因为用户可以使用非const版本(修改特定元素是必需的)来修改列数:

I want to offer the user a way of accessing and modifying particular elements by using the concatenated [] (i.e. m[1][1]). However, I don't want the user to be able to modify the dimension of the matrix or to modify the number of columns in one row. My current approach of offering the overloaded operator[] like below is not enough, since the user can use the non-const version (necessary for modifying particular elements) to modify the number of columns:

std::vector<double>& operator[](size_t r);
const std::vector<double>& operator[](size_t r) const;

通过执行m[0] = std::vector<double>(0).

有没有办法在保持双括号语法的同时防止这种崩溃?

我知道我可以像m(1, 1)一样使用operator(),但是我很好奇尝试使用双括号语法.

I am aware I could use operator() like m(1, 1), but I'm curious about trying to use the double bracket syntaxis.

推荐答案

您的operator[]可以返回定义了operator[]的代理对象.像这样:

Your operator[] can return a proxy object with operator[] defined. Something like this:

class Matrix2D
{
  std::vector<std::vector<double>> rows;

  class Proxy
  {
    friend class Matrix2D;

    std::vector<double> &v;

    Proxy(std::vector<double> &v) : v(v) {}

  public:
    double& operator[] (size_t c) const { return p[c]; }
  };

public:
  Proxy operator[] (size_t r)
  {
    return { rows[r]; }
  }
};

但是请注意,使用向量的向量表示2D矩阵通常是个坏主意,因为它非常不友好.如果仅存储大小为rows * cols的一个std::vector<double>并手动将其编入索引,则将更接近于实用性.

Note, however, that using a vector of vectors to represent a 2D matrix is usually a bad idea, as it's very cache-unfriendly. It would be much closer to practical usability if you store just one std::vector<double> of size rows * cols and index into it manually.

这篇关于用方括号运算符实现矩阵类的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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