您可以创建一个类模板,该模板将为您构造一个类似矩阵的对象,而不是像您尝试做的那样创建一个数组。这是我想出的,现在这个模板的整体设计或模式将适合您的条件,但生成内部矩阵的实际实现将取决于您的数据和您的意图。
#include <vector>
#include <iostream>
#include <conio.h>
template <class T, class U>
class Matrix {
private:
std::vector<T> m_lines;
std::vector<T> m_cols;
std::vector<U> m_mat;
std::size_t m_size;
std::size_t m_lineCount;
std::size_t m_colsCount;
public:
Matrix() {};
Matrix( const std::vector<T>& lines, const std::vector<T>& cols ) :
m_lines(lines),
m_cols(cols),
m_lineCount( lines.size() ),
m_colsCount( cols.size() )
{
addVectors( lines, cols );
}
void addVectors( const std::vector<T>& v1, const std::vector<T>& v2 ) {
m_lines = v1;
m_cols = v2;
m_lineCount = m_lines.size();
m_colsCount = m_cols.size();
for ( unsigned int i = 0; i < m_lineCount; ++i ) {
for ( unsigned int j = 0; j < m_colsCount); j++ ) {
// This will depend on your implementation and how you
// construct this matrix based off of your existing containers
m_mat.push_back(m_lines[i] & m_cols[j]);
}
}
m_size = m_mat.size();
}
std::size_t size() const { return m_size; }
std::size_t sizeRows() const { return m_lineCount; }
std::size_t sizelColumns() const { return m_colsCount; }
std::vector<U>& getMatrix() const { return m_mat; }
std::vector<T>& getLines() const { return m_lines; }
std::vector<T>& getColumns() const { return m_columns; }
bool operator[]( std::size_t idx ) { return m_mat[idx]; }
const bool& operator[]( std::size_t idx ) const { return m_mat[idx]; }
};
int main() {
std::vector<unsigned> v1{ 1, 0, 1, 1, 0 };
std::vector<unsigned> v2{ 0, 1, 1, 1, 0 };
Matrix<unsigned, bool> mat1( v1, v2 );
int line = 0;
for ( unsigned u = 0; u < mat1.size(); ++u ) {
line++;
std::cout << mat1[u] << " ";
if ( line == mat1.sizeRows() ) {
std::cout << "\n";
line = 0;
}
}
std::cout << "\nPress any key to quit.\n" << std::endl;
_getch();
return 0;
}
输出
0 1 1 1 0
0 0 0 0 0
0 1 1 1 0
0 1 1 1 0
0 0 0 0 0
使用这个模板类,您可以通过传入T 类型的两个向量来创建任何类型U 的矩阵。现在如何构造矩阵将取决于实现。但是这个类对于不同的类型是可重用的。
您可以有两个双精度类型的向量,并构造一个无符号字符矩阵,或者您可以有两个用户定义的类或结构类型的向量,并生成一个无符号值矩阵。这可能会在许多情况下帮助您。
注意: - 这确实会生成编译器警告,但没有错误,并且可以正确打印和显示,但是 MSVS 2015 生成的编译器警告是警告 C4800: unsigned int: forcing value to bool true or false (performance warning)
这是因为我正在对无符号值进行一些明智的 & 操作而生成的;但这就是为什么我将初始向量设置为传递给此类模板的构造函数以具有所有 1 和 0,因为这仅用于演示。
编辑 - 我对类进行了编辑,因为我注意到我有一个默认构造函数并且无法向其中添加向量,所以我添加了一个额外的成员变量和一个 addVectors 函数,并将实现从定义的构造函数移动到新函数,并最终在定义的构造函数中调用该函数。