一个自定义的向量和矩阵类在c++和操作符[]
A custom Vector and Matrix class in C++ and operator[]
我在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 );
};
相关文章:
- 为什么map有操作符[],set没有
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- c++新操作符通过libstdc++占用大量内存(67MB)
- 复制/移动操作符是否可以安全地用于实现复制/移动分配操作符
- 提升::精神::因果报应使用有条件的替代操作符(|)
- 促进几何体操作符
- 如果操作符delete没有实现,为什么不编译它
- 在使用放置新操作符时,我真的需要担心对齐问题吗
- 我怎样才能让getline操作符工作
- 在重载的全局new操作符中使用静态对象会导致核心转储运行时错误
- 提升ipc new和delete操作符
- 在c++中使用new操作符动态分配数组
- 操作符的大小在C++
- 如何将向量中的对象传递给操作符
- 一个更容易的拷贝分配操作符实现
- 如何重写复杂的c++代码行(嵌套的三元操作符)
- boost::make_shared没有调用(放置)操作符new
- 新操作符(以及malloc)无法分配~450MB的内存
- 类、异常和操作符
- 当delete操作符释放内存时,我为什么需要析构函数