简体   繁体   English

在 C++ 中使用向量的矩阵算术导致分段错误

[英]Matrix Arithmetic using Vectors in C++ causing segmentation faults

I'm having some issues passing vectors to functions.我在将向量传递给函数时遇到了一些问题。 My concern is not with my logic itself, as if I need to adjust later I will.我关心的不是我的逻辑本身,好像我以后需要调整一样。 My program requirements state that I must have separate functions that build the matrices, print the final matrix, and ones to perform the desired mathematical operations.我的程序要求 state 我必须有单独的函数来构建矩阵、打印最终矩阵以及执行所需数学运算的函数。 I'm not concerned with help on the math logic.我不关心数学逻辑的帮助。

It seems that I have the "hard' stuff down, for example, creating a vector of a vector, etc, but I'm having trouble passing the vectors to functions etc.似乎我有“硬”的东西,例如,创建一个向量的向量等,但我无法将向量传递给函数等。

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;
using std::vector;

void build();
void printMatrix(vector<vector<int> > );
int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );

int main(){
build();
addMatrix();
printMatrix(matrix3);
return 0;
}
//====================================================    
void build(){
//currently intended just to build 2x matrices of different increasing data
int k=0, l=5;
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
for( int i = 0; i < row; i++ ) {
    for ( int j = 0; j < col; j++ ){
        matrix[i][j] = k++;
        matrix2[i][j] = l++;
    }
}

I'm using Global Variables, because I want the Rows & Columns to stay the same and in the program, I'm only going to be able to call one of the mathematical functions at at time.我正在使用全局变量,因为我希望行和列保持不变,并且在程序中,我一次只能调用其中一个数学函数。

void printMatrix(vector<vector<int> > newMatrix3){
    for ( int i = 0; i < row; i++ ) {
        for ( int j = 0; j < col; j++ )
            cout<< setw ( 3 ) << newMatrix3[i][j] <<' ';
            cout<<'\n';
    }
 }
//=========================================
void addMatrix(){
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++)
            matrix3[i][j]=(matrix[i][j]+matrix2[i][j]);
    }

} }

This program compiles 100% so if you see a syntax error it's because my copy + paste messed up.这个程序可以 100% 编译,所以如果你看到语法错误,那是因为我的复制 + 粘贴搞砸了。 As soon as I enter the dimensions for the matrix, the program crashes with a segmentation fault.一旦我输入矩阵的维度,程序就会因分段错误而崩溃。 I'm very new to C++, so this is very frustrating.我对 C++陌生,所以这非常令人沮丧。 I'm also all ears to take suggestions on style/best practice.我也很乐意听取有关风格/最佳实践的建议。 I have the feeling that my use of global variables is not ideal....but I'm under instructions to make the arithmetic functions as re-usable as possible.我觉得我对全局变量的使用并不理想……但我正在接受指示,以使算术函数尽可能地可重用。 Also, I don't think I'm making the best use of functions.另外,我认为我没有充分利用功能。

Thank you.谢谢你。

Your global definitions of row , col , matrix , ... is the problem.您对rowcolmatrix的全局定义......是问题所在。

int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );

What's happening here is the following: row and col is now 0 and therefore all your matrices now have 0 rows and columns.这里发生的情况如下: rowcol现在是0 ,因此您的所有矩阵现在都有 0 行和列。

You can fix this by using the vector::resize() function after you get row and col from the user.在从用户那里获得rowcol后,您可以使用vector::resize() function 来解决这个问题。

cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
// Resize "matrix"
matrix.resize(row);
for(int i = 0; i < row; ++i) matrix[i].resize(col);
// Repeat for "matrix2" and "matrix3"    

Also, this means you don't have to "initialize" your matrix objects.此外,这意味着您不必“初始化”您的matrix对象。 So now you can just define them as:所以现在你可以将它们定义为:

vector<vector<int> > matrix;
vector<vector<int> > matrix2;
vector<vector<int> > matrix3;

Note:笔记:

  1. Think about using typedef to make your code look better.考虑使用typedef使您的代码看起来更好。
  2. You don't need them to be global variables.您不需要它们是全局变量。 You are using a vector and your printMatrix and addMatrix functions can call vector::size() to find out the size of your matrix.您正在使用vector ,您的printMatrixaddMatrix函数可以调用vector::size()来找出矩阵的大小。 You should rewrite those functions to take your matrix as an argument (lots of good advice here on that) and then work on them.您应该重写这些函数以将您的矩阵作为参数( 这里有很多好的建议),然后对它们进行处理。

Matrices are created when row and col are zero, so any attempt to access their contents results in a segmentation fault.当 row 和 col 为零时创建矩阵,因此任何访问其内容的尝试都会导致分段错误。 You need to first read row and col, and then build the matrices.您需要先读取行和列,然后构建矩阵。 This excludes making them global variables.这不包括使它们成为全局变量。

You're not resizing the vectors/matrices to the dimensions that the user put in - they're stuck at row == 0, col == 0 because that's what the two variables default to.您没有将向量/矩阵的大小调整为用户输入的尺寸 - 它们停留在 row == 0, col == 0 因为这是两个变量的默认值。

You'd want to look at vector::resize() to update the dimensions of the vector after the user input.您需要查看vector::resize()以在用户输入后更新向量的尺寸。

You never add the elements to the matrices, ie.您永远不会将元素添加到矩阵中,即。 matrix and matrix2 are empty when you call build.调用 build 时, matrixmatrix2为空。 You need to size the matrix after your receive the users input.您需要在收到用户输入后调整矩阵的大小。

void build(){
//currently intended just to build 2x matrices of different increasing data
int k=0, l=5;
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
matrix.resize(row);
matrix2.resize(row);
for( int i = 0; i < row; i++ ) {
    matrix[i].resize(col, 0);
    matrix2[i].resize(col, 0);
    for ( int j = 0; j < col; j++ ){
        matrix[i][j] = k++;
        matrix2[i][j] = l++;
    }
}
int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );

This creates the vectors while row and col are still zero, long before you read in the values.这将创建向量,而rowcol仍然为零,早在您读取值之前。

Your program segfault because you create matrix with a size of (0,0).您的程序段错误,因为您创建了大小为 (0,0) 的矩阵。 When you try to set elements: segfault:)当您尝试设置元素时:segfault :)

Suggestions:建议:

  • use a matrix library:)使用矩阵库:)
  • if you want to learn: create a Matrix object that you will create with the correct size如果您想学习:创建一个矩阵 object,您将使用正确的大小创建该矩阵
  • please avoid globals !请避免使用全局变量!
  • flag your question as homework;)将您的问题标记为作业;)

For your class try to implement something like:对于您的 class 尝试实现类似的东西:

class Matrix
{
    public:
    Matrix(unsigned rows, unsigned columns);
    void add(const Matrix&)
    void print();

    // etc.
};

my2c my2c

You must use push_back to initialize elements of a vector, or you must size the vectors before using [index]= form.您必须使用 push_back 来初始化向量的元素,或者您必须在使用 [index]= 形式之前调整向量的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM