I am working on a program for homework and ran into a strange problem. When trying to get the size of a 2D vector using the size() function, I get seemingly random large integers which stop my program from running. I need the size to access elements in the vector.
My header file:
#ifndef _MATRIX_H
#define _MATRIX_H
#include <iostream>
#include <vector>
class Matrix {
private:
//int dimension;
std::vector< std::vector<int> > matrix;
public:
Matrix();
Matrix(std::vector< std::vector<int> >);
void print();
Matrix operator-(Matrix operand);
};
#endif
My implementation file:
#include "Matrix.h"
#include <iostream>
#include <vector>
// Default constructor
Matrix::Matrix() {
}
// Parameterized constructor
Matrix::Matrix(std::vector< std::vector<int> >) {
}
void Matrix::print() {
std::cout << "Size of matrix in print() " << matrix.size() << std::endl;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
Matrix Matrix::operator-(Matrix operand) {
Matrix difference;
std::vector< std::vector<int> > diffMatrix;
diffMatrix.resize(matrix.size());
for (int i = 0; i < matrix.size(); i++ ) {
diffMatrix[i].resize(matrix.size());
}
difference.matrix = diffMatrix;
if (operand.matrix.size() == matrix.size()) {
for (int i = 0; i < operand.matrix.size(); i++) {
for (int j = 0; j < operand.matrix.size(); j++) {
difference.matrix[i][j] = matrix[i][j] - operand.matrix[i][j];
}
}
}
}
and my main.cpp file:
#include "Matrix.h"
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
vector< vector<int> > testMatrixOne(4);
vector< vector<int> > testMatrixTwo(4);
// Creating a test matrix
testMatrixOne = {{1,2},{3,4}};
testMatrixTwo = {{5,6},{7,8}};
// Create Matrix object
Matrix matrixOne(testMatrixOne);
Matrix matrixTwo(testMatrixTwo);
// Create Matrix to store difference
Matrix diff;
diff = matrixOne - matrixTwo;
diff.print();
return 0;
}
I have simplified my code and hardcoded in two matrices. When running the program, the size() will return a very large integer. I have spent several hours searching online but couldn't find out what's the cause of this. Why is the size() function doing this?
The problem is unfortunately that:
Matrix Matrix::operator-(Matrix operand) {
never returns a value. This causes undefined behaviour, and the symptoms you saw were the result of the -
appearing to return garbage.
At the end of the function, you meant to have:
return difference;
}
The C++ standard doesn't require compilers to warn about this, but it's still nice if they do warn. My version of g++ doesn't (even with -Wall), however adding the flag -Wreturn-type
does produce a warning. IDK why this isn't part of -Wall
, at least for simple cases like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With