c++ - 似乎是乘法和分配新值 multVact 的问题
问题描述
创建两个向量并将值分配给这两个向量,然后将这两个向量相乘。(矩阵乘法)。在乘法函数中给出分段错误错误。尝试访问范围之外的位置是否与此有关?
#include<iostream>
#include <vector>
using namespace std;
int n;
vector <int> mat1Rows;
vector <int> mat2Rows;
vector <int> multRows;
vector <vector<int> > mat1;
vector <vector<int> > mat2;
vector <vector<int> > multMat;
void assignValues(int num){
for(int i = 0; i < num; i++){
for(int j = 0; j < num; j++){
mat1Rows.push_back(j);
mat2Rows.push_back(j);
}
mat1.push_back(mat1Rows);
mat2.push_back(mat2Rows);
mat1Rows.clear();
mat2Rows.clear();
}
}
void multiply(int n){
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
for(int k = 0; k < n; ++k){
multMat[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
void displayMult(int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cout << multMat[i][j] << " " ;
}
cout << endl;
}
}
int main(){
cout << "Enter the size of the matrix: ";
cin >> n;
assignValues(n);
multiply(n);
displayMult(n);
return 0;
}
解决方案
multMat[i][j] += mat1[i][k] * mat2[k][j];
内部没有内存,multMat
因为您没有为元素保留任何内存。你需要告诉vector分配内存。您可以使用resize来为元素分配内存并更改向量的大小。
void multiply(int n) {
multMat.resize(n);
for (auto&& i : multMat) {
i.resize(n);
}
... rest of the code ...
}
std::vector::operator[]
不执行边界检查。因此,如果您指定超出允许范围的索引并尝试将某些内容分配给返回的引用,则会发生未定义的行为。用于std::vector::at()
始终确保您的索引有效。
推荐阅读
- powerbi - Power BI DAX:ALLSELECTED,但一列除外
- asp.net-core - 我想使用 Asp MVC Core 2.0 创建美国日期格式到印度日期格式
- python - 替换列表的值,知道它在 Pandas DataFrame 中的索引和值
- django - Boto3/Django 存储类中的访问请求
- javascript - 如何使用图像映射编写区域的文本中心?
- ssl - 如何在 XAMPP(Windows)中使用公共 IP 地址配置自签名 ssl?
- python - GUI中的描述照片查看器 - Python
- python - 在 NumPy 中查找特定长度的连续重复
- java - ViewAdapter 正在复制列表视图中的选定项目
- javascript - 字符串包含两个语句