I am working on a homework program and am facing some strange problem. When I try to get the size of a 2D vector using the size () function, I get seemingly random large integers that stop the execution of my program. I need a size to access the elements in the vector.
My header file:
#ifndef _MATRIX_H
#define _MATRIX_H
#include <iostream>
#include <vector>
class Matrix {
private:
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>
Matrix::Matrix() {
}
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);
testMatrixOne = {{1,2},{3,4}};
testMatrixTwo = {{5,6},{7,8}};
Matrix matrixOne(testMatrixOne);
Matrix matrixTwo(testMatrixTwo);
Matrix diff;
diff = matrixOne - matrixTwo;
diff.print();
return 0;
}
I simplified my code and hardcoded in two matrices. When the program starts, size () will return a very large integer. I spent several hours on the Internet, but could not understand what was the reason for this. Why does the size () function do this?
source
share