一个很简单的矩阵求幂模板类的程序,但是在vector<vector<T>> temp(n,vector<T>(n));这一句不能执行,会卡死。下面是完整的代码和输出
// ### 方阵的幂运算,n * n 矩阵的m次幂
// * 1)使用类进行封装
// * 2)使用C++操作符重载(可选)
// * 3)使用模板(可选)
// 你必须定义一个 `main()` 函数入口。
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class Matrix{
public:
Matrix(int n){
this->data.assign(n,vector<T>(n));
}
Matrix(vector<vector<T>> m){
this->data = m;
}
~Matrix(){
}
Matrix operator * (Matrix& m2){
printf("%d\n",__LINE__);
T a = 3;
printf("%d\n",a);
printf("a = %d\n",__LINE__);
vector<vector<T>> temp(n,vector<T>(n));
printf("%d\n",__LINE__);
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
for(int k = 0;k < n;k++){
temp[i][j] += this->data[i][k] * m2.data[k][j];
}
}
}
Matrix res(temp);
printf("%d\n",__LINE__);
return res;
}
Matrix operator ^(int m){
printf("%d, m = %d\n",__LINE__,m);
if(m == 0) {
vector<vector<T>> temp(n,vector<T>(n));
for(int i = 0;i < n;i++){
temp[i][i] = 1;
}
return Matrix(temp);
}
if(m == 1) return (*this);
Matrix temp = (*this) ^ (m / 2);
temp = temp * temp;
if(m % 2 == 0){
return temp;
}else{
return temp * (*this);
}
}
void print(){
for(vector<T> vt:data){
for(T e:vt){
cout<<e<<" ";
}
cout<<endl;
}
}
vector<vector<T>> data;
int n;
};
int main()
{
int N = 3;
vector<vector<int>> v(3,vector<int>(3));
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
v[i][j] = i * N + j + 1;
}
}
Matrix<int> mt(v);
mt.print();
Matrix<int> res = mt ^ 4;
res.print();
return 0;
}
代码输出(行号不是完全对应,a = 3根据a = 3这一行即可):
可见T代表int类型的确是传进去了,但为什么vector<vector<T>> temp(n,vector<T>(n));会卡死不动呢。运行程序的同时,使用top命令查看机器状态,prog就是编译后的程序,可以发现vector<vector<T>> temp(n,vector<T>(n))这一句打满了CPU,内存也一直嗖嗖的涨。
过了一会儿报了段错误
可见vector<vector<T>> temp(n,vector<T>(n))这一句会不断的申请内存。
但是为什么会导致这个问题呢?是C++标准中的UB吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)