首页 > 解决方案 > 似乎是乘法和分配新值 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;   
}

标签: c++segmentation-faultvertices

解决方案


 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()始终确保您的索引有效。


推荐阅读