一个自定义的向量和矩阵类在c++和操作符[]

A custom Vector and Matrix class in C++ and operator[]

本文关键字:c++ 操作符 一个 自定义 向量      更新时间:2023-10-16

我在c++中有一个依赖于原始指针的向量类。我不使用std::vector,因为我需要从特定情况下的原始指针创建向量对象。下面是我的类的一个非常简单的例子:

template <typename T>
class Vector
{ ...
  private:
    T * m_data; int m_size; bool dontFree; ...
  public:
    Vector(T *const ptr, int size) { m_data = ptr; m_size = size; dontFree = true; }
    Vector(int size, T val) {  ...  dontFree = false; }
    ~Vector(): {   if(!dontFree) delete [] m_data; }
    T& operator[](const size_type index);
};

同样,我有矩阵数据类型,也存储数据在原始指针,可以使用向量来支持[][],因为它在c++中是不允许的,像:

template<typename T>
class Matrix
{
  private:
   T * m_data; ...
 public:
  ... 
  Vector<T>& operator[](const int rowIndex)
  {
     return Vector<T>(&m_data[rowSize * rowIndex], rowSize);
  }
}

我如何有效地实现运算符[]为矩阵返回一个向量,以便我可以写代码,下面的内容:

Matrix<int> m(5,5);
m[1][1] = 10;
int temp = m[1][2];

请建议考虑复制构造函数的开销等

创建一个代理类,重载操作符[],您可以访问您的矩阵数组。像这样:

template<typename T>
class Proxy
{
public:
    Proxy(T * tp)
        :rowStart(tp)
    {}
    T & operator[](const int columnIndex)
    {
        return rowStart[columnIndex];
    }
private:
    T * rowStart;
};

那么你的矩阵类的操作符[]可以返回其中一个,像这样:

Proxy<T> operator[](const int rowIndex)
{
     return Proxy<T>(m_data + rowSize * rowIndex);
}

当然,这还不完整,但它应该让你开始。

您应该按值返回向量以使您的代码正确。如果你的vector在复制构造函数中做了很多工作,你也可以编写一个小代理。

如果你将operator[]实现为内联方法(例如,不要将实现移动到cpp),那么好的编译器应该优化你的代码并消除不必要的复制。

但是如果你对性能很着迷,那么你可以从操作符返回一个原始指针:

... 
T* operator[](const int rowIndex)
{
  return m_data + rowSize * rowIndex;
}
...
int temp = m[1][2];

但是是一个危险的方法!

在实现多维矩阵时,建议不要重载operator[],而是重载具有多维的operator()。有几个原因,你可以在c++常见问题手册

中阅读。
template <typename T>
class Matrix {
public:
   typedef std::size_t size_type;
   typedef T & reference;
   typedef T const & const_reference;
   const_reference operator()( size_type x, size_type y ) const;
   reference operator()( size_type x, size_type y );
};