c++ - 动态分配“向量”类的数组
问题描述
所以我必须实现一个'Matrix'抽象类,它使用指向'Vector'的指针数组作为其内容。
'Square_matrix' 是 Matrix 的实际实现。
class Vector
{
int dim; // dimension
int* a; // actual array
public:
Vector(int n)
{
dim = n;
a = new int[n];
}
};
class Matrix //it will be an abstract class
{
protected:
Vector* v;
public:
Matrix(int col, int lin)
{
//here is my problem
}
};
class Square_matrix : public Matrix
{
int dim;
public:
Square_matrix(int dim)
: Matrix(dim, dim) { this-> dim = dim; }
};
我怎样才能使这样的工作?
Matrix(int lin, int col)
{
v = new (Vector*)[lin];
for(int i = 0; i < lin; i++)
{
v[i] = new Vector(col);
}
}
解决方案
当然使用std::vector<std::vector<int>>
可能不是你想做的;D。
关于代码中的问题 --- 你在 Vector 中保留整数:
int* a; // int a[];
并且您将向量保留在矩阵中
Vector* v; // Vector v[]
但是在您的构造函数中,您每次都尝试分配新向量,因此为了保持一致,您实际上应该在 v 的声明中添加一颗星:
Vector** v; // Vector* v[];
...
Matrix(int lin, int col)
{
v = new Vector*[lin];
for(int i = 0; i < lin; i++)
{
v[i] = new Vector(col);
}
}
或者,您可以使用更复杂的解决方案,保持 v 的声明,因为它现在在那里,并使用placement new:
Vector* v; // Vector v[]
...
Matrix(int col, int lin) // what if somebody mixes order of col and lin?
{
// watch out for alignment if you do such tricks!!!
v = reinterpret_cast<Vector*>(new char[sizeof(Vector)*lin]);
for(int i = 0; i < lin; i++)
{
new (v+i) Vector(col);
}
}
当然,不要忘记析构函数、异常安全等等……
推荐阅读
- reactjs - 使用 tabBarIcon 反应本机问题 - createElement:类型无效
- python - re.search 获取字符串的最后 7 个字符
- javascript - 基于输入表单生成动态发票概览的结构
- html - ag-grid 表格溢出屏幕
- c - 为什么 printf 不接受指针作为参数
- spring - 用外部属性覆盖 spring-boot application.properties
- python-3.x - 我可以在 DBeaver 中查看连接字符串并将其复制以在 Python 中连接到 DB2 吗?
- amazon-web-services - 如何在动态清单(Ansible)中使用实例 ID 而不是 tag_Name?
- amazon-web-services - SQS 重复数据删除 ID 和项目更新
- python - 如何从服务器上的 bash 脚本在虚拟环境中执行脚本?