I am trying to overload the ostream << operator in my Matrix class, but I keep getting the following error:
Expected constructor, destructor, or type conversion before token &
Matrix::ostream& operator<<(const Matrix& matrix)
{
for (int r = 0; r < matrix.getNumrows(); r++)
{
cout << matrix.getPoint(r, 0);
for (int c = 0; c < matrix.getNumcolumns(); c++)
{
cout << " " << matrix.getPoint(r,c);
}
cout << endl;
}
return stream;
}
This is the rest of my class
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "Matrix.h"
using namespace std;
Matrix::Matrix()
{
}
Matrix::Matrix(int rows, int cols) {
numRows=rows;
numCols=cols;
//col=new double[cols];
mx=new double*[rows];
for ( int i=0; i < rows; i++ ) {
mx[i] = new double[cols];
// initalize each element of the new row.
for ( int c=0; c < cols; c++ ) {
mx[i][c] = 0.0;
}
}
}
Matrix::Matrix(const Matrix &theMatrix) {
int rows=theMatrix.numRows;
int cols=theMatrix.numCols;
numRows = rows;
numCols = cols;
mx=new double*[rows];
for ( int r=0; r < rows; r++ ) {
mx[r] = new double[cols];
// copy each element of the new row.
for ( int c=0; c < cols; c++ ) {
mx[r][c] = theMatrix.mx[r][c];
}
}
}
void Matrix::setMatrix(string file)
{
/* read the file */
fstream inputStream(file.c_str());
if(inputStream.is_open() )
{
string line;
stringstream ss;
getline(inputStream, line);
ss.clear();
ss.str(line);
ss >> numRows >> numCols;
mx=new double*[numRows];
for ( int i=0; i < numRows; i++ ) {
mx[i] = new double[numCols];
// initalize each element of the new row.
for ( int c=0; c < numCols; c++ ) {
mx[i][c] = 0.0;
}
}
//now loop to get values
for(int row=0; row<numRows; row++)
{
getline(inputStream, line);
ss.clear();
ss.str(line);
//now get every value in the line
for(int col=0; col<numCols; col++)
{
double current;
ss >> current;
mx[row][col] = current;
}//end reading values of row
}//end reading rows
}
//close the file
inputStream.close();
}
int Matrix::getNumrows()
{
return numRows;
}
int Matrix::getNumcolumns()
{
return numCols;
}
void Matrix::printPoint()
{
for ( int r=0; r < numRows; r++ )
{
for ( int c=0; c < numCols; c++ )
{
cout << mx[r][c] << " ";
}
cout << endl;
}
cout << endl;
}
bool Matrix::getIsSquared()
{
if( numRows == numCols )
{
return true;
}
else
{
return false;
}
}
double Matrix::det()
{
double det=0.0;
if(numRows!=numCols)
{
cout << "Number Rows must be same as number Colums\n";
}
if(numRows==2)
{
det=(mx[0][0]*mx[1][1])-(mx[0][1]*mx[1][0]);
}
else
{
for(int i=0 ; i<numCols ; i++)
{
Matrix temp(numRows-1,numCols-1);
for(int j=0 ; j<numRows-1 ; j++)
{
for(int k=0 ; k<numCols-1 ; k++)
{
if(k<i)
temp.mx[j][k]=mx[j+1][k];
else
temp.mx[j][k]=mx[j+1][k+1];
}
}
det+=pow(-1.0,i)*mx[0][i]*temp.det();
}
}
return det;
}
double Matrix::getPoint(int row, int col)
{
return mx[row][col];
}
Matrix Matrix::operator +(const Matrix &right) const
{
Matrix result(numRows,numCols);
if ( right.numRows != numRows || right.numCols != numCols )
{
cout << "\nError while adding matricies, the two must have the same dimentions.\n";
}
else
{
for ( int r=0; r < numRows; r++ )
{
for ( int c=0; c < numCols; c++ )
{
result.mx[r][c] = (this->mx[r][c]) + (right.mx[r][c]);
}
}
}
return result;
}
If you want to overload the ostream operator<< for your class, you need to use either a friend function or a non-member function because the ostream object appears on the left-hand side of the expression (it's written as os << my_matrix).
std::ostream& operator<<(std::ostream& os, const Matrix& matrix) { /* ... */ }
It looks like you are trying to implement it as a member function, but that should actually look like:
std::ostream& Matrix::operator<<(const Matrix& matrix) { /* ... */ }
This won't work because when you implement an operator overload as a member function, the type of the object on the left hand side of the expression is the same as the type of the class of which the overload is a member (so, in this case, you'd have to write my_matrix1 << my_matrix2, which isn't what you want).
Inside of the overload, you shouldn't write to cout directly; you should write to the ostream object that is passed as an argument to the function.
Write it as:
ostream& operator<<(ostream& os, const Matrix& matrix)
{
for (int r = 0; r < matrix.getNumrows(); r++)
{
os << matrix.getPoint(r, 0);
for (int c = 0; c < matrix.getNumcolumns(); c++)
{
os << " " << matrix.getPoint(r,c);
}
os << endl;
}
return os;
}
and it will work. It does not have to be a member function of Matrix.
Just change
Matrix::ostream& operator<<(const Matrix& matrix)
to
std::ostream& operator<< (std::ostream &stream, const Matrix &matrix)
It'll be a stand-alone function .. and should work just fine.
Related
I have written a c++ program to check whether a matrix is sparse or not. The syntax errors which come up are as follows:
main.cpp:56:8: error: deduced class type ‘matrix’ in function return type
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:11:7: note: ‘template class matrix’ declared here
class matrix
^~~~~~
main.cpp:56:8: error: prototype for ‘matrix matrix::add(matrix)’ does not match any in class ‘matrix’
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:19:9: error: candidate is: matrix matrix::add(matrix&)
matrix add(matrix&);
^~~*
And the program is:
#include<iostream>
#include <exception>
using namespace std;
class mismatchDimension:public exception
{
public:
void error_Msg () const;
};
template < class T >
class matrix
{
int row;
int col;
T ele[10][10];
public:
void get ();
bool check_Sparse ();
matrix add (matrix &);
void print ();
};
//no changes to be made to the above code
void mismatchDimension::error_Msg () const const //Error printing method
{
cout << "Dimension of matrices do not match" << endl;
}
template < class T >
void matrix < T >::get () //Element input of matrix
{
cin >> row;
cin >> col;
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
cin >> ele[j][i];
}
}
template < class T >
bool matrix < T >::check_Sparse () //Check if the matrix is sparse
{
int i, j, t;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (ele[j][i] == 0) ++t;
}
}
if (t > (row * col) / 2) return true;
else return false;
}
template < class T >
matrix matrix < T >::add (matrix r) //Addition of the matrices
{
mismatchDimension z;
int i, j;
matrix < T > w;
if (row != r.row && col != r.col) throw z;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
w.ele[j][i] = ele[j][i] + r.ele[j][i];
}
}
return w;
}
template < class T >
void matrix < T >::print () //printing the matrix
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++) cout << ele[j][i] << endl;
}
}
// no changes to be made below
int
main ()
{
matrix < int >m1, m2, m3;
m1.get ();
m2.get ();
try
{
m3 = m1.add (m2);
m3.print ();
} catch (mismatchDimension & m)
{
m.error_Msg ();
}
if (m1.check_Sparse ())
cout << "Matrix is sparse" << endl;
else
cout << "Matrix is not sparse" << endl;
}
There are multiple issues:
In the declaration matrix add (matrix &); you pass by reference while in the definition matrix matrix < T >::add (matrix r) you pass by value. Choose only one.
The return type specification and the parameter type should be provided with template argument:
template <class T>
matrix<T> matrix<T>::add (matrix r)
{
...
}
Note that since C++11, you can also omit template argument in the return type with trailing return type declaration:
template <class T>
auto matrix<T>::add (matrix r) -> matrix
{
...
}
I'm just going to preface this with the fact that I'm new to C++ so it's quite possible there's just a stupid error here, but I can't find it.
I'm just trying to overload the increment operator in a friend function. Everything compiles perfectly and everything works if I explicitly call the postfix increment overload:
operator++(*test, 0);
Every element in the matrix is incremented and the program prints it out using cout perfectly. The problem is when I try to do the normal ++ increment test++; it appears as though something wrong happens with the test pointer to where when it tries to print the test object it doesn't print anything.
Any idea what's going on? I'm clueless. Here's the code I'm working with...
Compile & Run
g++ -o App App.cpp Matrix.cpp
./App
App.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;
#define X 9
int main(int argc, char *argv[])
{
// Start the actual program here
Matrix* test = new Matrix(3,3);
// Row 1
test->setElement(0,0,1);
test->setElement(0,1,2);
test->setElement(0,2,3);
// Row 2
test->setElement(1,0,4);
test->setElement(1,1,5);
test->setElement(1,2,6);
// Row 3
test->setElement(2,0,7);
test->setElement(2,1,8);
test->setElement(2,2,9);
operator++(*test, 0);
//test++;
//++test;
// Print the Matrix object
cout << *test << endl;
}
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std;
class Matrix {
friend ostream& operator<<(ostream&, const Matrix&);
friend Matrix& operator++(Matrix&); // prefix increment
friend Matrix& operator++(Matrix&, int); // postfix increment
private:
int rows;
int cols;
int** elements;
public:
// Constructors
Matrix(int);
Matrix(int,int);
Matrix(const Matrix&);
// Define setters
void setElement(int,int,int);
// Define getters
int getRowCount();
int getColCount();
int getElementAt(int,int);
void increment();
// Destructor
~Matrix();
};
#endif
Matrix.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;
//===================================
// DEFINE [CON]/[DE]STRUCTORS
//===================================
// Constructor for creating square matricies
Matrix::Matrix(int _size) {
rows = _size;
cols = _size;
elements = new int*[_size];
for (int i = 0; i < _size; i++) {
elements[i] = new int[_size];
}
}
// Constructor for supporting non-square matricies
Matrix::Matrix(int _rows, int _cols) {
rows = _rows;
cols = _cols;
elements = new int*[_rows];
for (int i = 0; i < _rows; i++) {
elements[i] = new int[_cols];
}
}
// Copy constructor
Matrix::Matrix(const Matrix& mat1) {
Matrix(mat1.rows, mat1.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
elements[i][j] = mat1.elements[i][j];
}
}
}
// Destructor
Matrix::~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] elements[i];
}
delete[] elements;
}
//===================================
// DEFINE SETTER FUNCTIONS
//===================================
void Matrix::setElement(int row, int col, int newElement) {
if (row > rows-1 || row < 0)
throw "Row out of index";
if (col > cols-1 || col < 0)
throw "Column out of index";
elements[row][col] = newElement;
}
//===================================
// DEFINE GETTER FUNCTIONS
//===================================
int Matrix::getRowCount() { return rows; }
int Matrix::getColCount() { return cols; }
int Matrix::getElementAt(int row, int col) {
if (row > rows-1 || row < 0)
throw "Row out of index";
if (col > cols-1 || col < 0)
throw "Column out of index";
return elements[row][col];
}
//===================================
// OVERRIDE OPERATOR FUNCTIONS
//===================================
// Print the Matrix to the output stream
ostream& operator<<(ostream& out, const Matrix& mat) {
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
out << mat.elements[i][j] << " ";
}
out << endl;
}
return out;
}
// Prefix. Increment immediately and return the object.
Matrix& operator++(Matrix& mat) {
cout << "Prefix ++ operator" << endl;
// Increment all elements in the object by 1
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
mat.elements[i][j] += 1;
}
}
return mat;
}
// Postfix. Return the current object and "save" the incremented.
Matrix& operator++(Matrix& mat, int x) {
cout << "Postfix ++ operator" << endl;
// Save the current values
Matrix* curVals = new Matrix(mat);
// Increment the object
++(mat);
// Return the unincremented values
return *curVals;
}
test++ increments the value of test, so that it will point to the memory after your Matrix object. You need to dereference the pointer to get a Matrix object, then apply the increment to that.
What you want is (*test)++ or ++*test.
I'm trying to figure out why my program fails when I run. So far when I run my program it fails on me. I debugged the error and it brings me to dbgdel.cpp. Line 32 " _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));". I've searched for the answer to no avail, but it has something to do with my memory leak?
Here is my header:
#include <iostream>
using namespace std;
namespace project
{
#ifndef MATRIX_H
#define MATRIX_H
typedef int* IntArrayPtr;
class Matrix
{
public:
friend ostream& operator<<(ostream& out, Matrix& object);
//friend istream& operator>>(istream& in, Matrix& theArray);
//Default Constructor
Matrix();
Matrix(int max_number_rows, int max_number_cols, int intial_value);
//Destructor
~Matrix();
//Copy Constructor
Matrix(const Matrix& right_side);
//Assignment Operator
Matrix& operator=(const Matrix& right_side);
void Clear();
int Rows();
int Columns();
bool GetCell(int x,int y, int& val);
bool SetCell(int x,int y, int val);
int getNumber(int r, int c);
//void Debug(ostream& out);
private:
int initialVal;
int rows;
int cols;
IntArrayPtr *m;
};
#endif
}
My implementation file:
#include <iostream>
#include "Matrix.h"
using namespace project;
using namespace std;
namespace project
{
Matrix::Matrix()
{
typedef int* IntArrayPtr;
IntArrayPtr *m = new IntArrayPtr[1];
for(int i = 0; i < 1; i++)
m[i] = new int[1];
for(int r = 0; r < 1; r++)
for(int c = 0; c < 1;c++)
m[r][c] = 0;
}
Matrix::Matrix(int max_number_rows, int max_number_cols, int initial_value)
{
initialVal = initial_value;
rows = max_number_rows;
cols = max_number_cols;
IntArrayPtr *m = new IntArrayPtr[rows];
for(int i = 0; i < rows; i++)
m[i] = new int[cols];
for(int r = 0; r < max_number_rows; r++)
for(int c = 0; c < max_number_cols;c++)
m[r][c] = initial_value;
}
Matrix::~Matrix()
{
for(int i = 0; i <= rows; i++)
delete [] m[i];
delete [] m;
}
void Matrix::Clear()
{
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols;c++)
m[r][c] = initialVal;
}
int Matrix::Rows()
{
return rows;
}
int Matrix::Columns()
{
return cols;
}
bool Matrix::GetCell(int x,int y, int& val)
{
if(x < rows || y < cols)
return false;
else
{
val = m[x - 1][y - 1];
return true;
}
}
bool Matrix::SetCell(int x, int y, int val)
{
if(x < rows || y < cols)
return false;
else
{
m[x - 1][y - 1] = val;
return true;
}
}
int Matrix::getNumber(int r, int c)
{
return m[r][c];
}
ostream& operator<<(ostream& out, Matrix& object)
{
for(int r = 0; r < object.rows; r++)
{
for(int c = 0; c < object.cols; c++)
{
out << " " << object.m[r][c];
}
out << endl;
}
return out;
}
Matrix& Matrix::operator=(const Matrix& right_side)
{
if (this != &right_side)
{
rows = right_side.rows;
cols = right_side.cols;
delete[] m;
IntArrayPtr *m = new IntArrayPtr[rows];
for(int i = 0; i < rows; i++)
m[i] = new int[cols];
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols;c++)
m[r][c] = right_side.initialVal;
}
return *this;
}
/*
void Matrix::Debug(ostream& out)
{
out << "Number of rows = " << rows << endl;
out << "Number of columns = " << cols << endl;
out << "Initializer = " << initialVal << endl;
out << "Current contents of the matrix: " << endl;
out << m << endl;
}
*/
/*
istream& operator >>(istream& in, Matrix& theArray)
{
in >>
}
void interfaceMatrix()
{
int userChoice, rows, columns, value;
cout << "Default matrix or custom(1 for default, 0 for custom): ";
cin >> userChoice;
if (userChoice == 1)
{
Matrix object;
return object;
}
else if(userChoice == 0)
{
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> columns;
cout << "Enter initial value of each element: ";
cin >> value;
if(rows <= 0 || columns <= 0)
{
cout << "Invalid input." << endl;
exit(1);
}
else
{
Matrix object(rows, columns, value);
return object;
}
}
else
{
cout << "Invalid choice." << endl;
exit(1);
}
}
*/
}
In my driver I just put Matrix test(2,2,2), so I can create a 2 x 2 array with initial value of 2 for each element. I get the above error.
You are allocating rows number of rows, but deallocating rows+1 number of rows.
Check the destructor. <= must be <.
Besides this there are a lot of other [potential] errors in your code:
you are setting the local m variable instead of setting the m data member of your class (that's why I have the convention to always precede data members by m_ to prevent this kind of confusion). This error appears both in the constructor and the assignment operator.
you use rows to allocate the matrix, but max_number_rows to initialize the matrix. Although it works correctly now, it may lead to errors if row is initialized differently later (e.g. if row is initialized with std::max(max_number_rows,1000). Your code in the assignment operator is better.
your if-test in GetCell and SetCell is incorrect. It should probably be >= instead of <
the assignment operator copies the size of the matrix, but assigns all cells an initialValue. This is not an assignment. This implementation might/will confuse the rest of the code.
the typedef of IntArrayPtr is unnecessary
two issues:
You are not allocating any value into the "m" member of your object, you are allocating into local variables named "m"
you are over deallocating by looping from i=0 to i <= rows, you want i=0 to i < rows
First off i know the multiplying part is wrong but i have some questions about the code.
1. When i am overloading my operator+ i print out the matrix using cout << *this then right after i return *this and when i do a+b on matix a and matix b it doesnt give me the same thing this is very confusing.
2. When i make matrix c down in my main i cant use my default constructor for some reason because when i go to set it = using my assignment operator overloaded function it gives me an error saying "expression must be a modifiable value. although using my constructor that sets the row and column numbers is the same as my default constructor using (0,0).
3. My assignment operator= function uses a copy constructor to make a new matrix using the values on the right hand side of the equal sign and when i print out c it doesn't give me anything
Any help would be great this is my hw for a algorithm class which i still need to do the algorithm for the multiplying matrices but i need to solve these issues first and im having a lot of trouble please help.
//Programmer: Eric Oudin
//Date: 10/21/2013
//Description: Working with matricies
#include <iostream>
using namespace std;
class matrixType
{
public:
friend ostream& operator<<(ostream&, const matrixType&);
const matrixType& operator*(const matrixType&);
matrixType& operator+(const matrixType&);
matrixType& operator-(const matrixType&);
const matrixType& operator=(const matrixType&);
void fillMatrix();
matrixType();
matrixType(int, int);
matrixType(const matrixType&);
~matrixType();
private:
int **matrix;
int rowSize;
int columnSize;
};
ostream& operator<< (ostream& osObject, const matrixType& matrix)
{
osObject << endl;
for (int i=0;i<matrix.rowSize;i++)
{
for (int j=0;j<matrix.columnSize;j++)
{
osObject << matrix.matrix[i][j] <<", ";
}
osObject << endl;
}
return osObject;
}
const matrixType& matrixType::operator=(const matrixType& matrixRight)
{
matrixType temp(matrixRight);
cout << temp;
return temp;
}
const matrixType& matrixType::operator*(const matrixType& matrixRight)
{
matrixType temp(rowSize*matrixRight.columnSize, columnSize*matrixRight.rowSize);
if(rowSize == matrixRight.columnSize)
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
temp.matrix[i][j] = matrix[i][j] * matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot multiply matricies that have different size rows from the others columns." << endl;
}
return temp;
}
matrixType& matrixType::operator+(const matrixType& matrixRight)
{
matrixType temp;
if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
{
temp.setRowsColumns(rowSize, columnSize);
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
temp.matrix[i][j] = matrix[i][j] + matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot add matricies that are different sizes." << endl;
}
return temp;
}
matrixType& matrixType::operator-(const matrixType& matrixRight)
{
matrixType temp(rowSize, columnSize);
if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
matrix[i][j] -= matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot subtract matricies that are different sizes." << endl;
}
return *this;
}
void matrixType::fillMatrix()
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
cout << "Enter the matix number at (" << i << "," << j << "):";
cin >> matrix[i][j];
}
}
}
matrixType::matrixType()
{
rowSize=0;
columnSize=0;
matrix = new int*[rowSize];
for (int i=0; i < rowSize; i++)
{
matrix[i] = new int[columnSize];
}
}
matrixType::matrixType(int setRows, int setColumns)
{
rowSize=setRows;
columnSize=setColumns;
matrix = new int*[rowSize];
for (int i=0; i < rowSize; i++)
{
matrix[i] = new int[columnSize];
}
}
matrixType::matrixType(const matrixType& otherMatrix)
{
rowSize=otherMatrix.rowSize;
columnSize=otherMatrix.columnSize;
matrix = new int*[rowSize];
for (int i = 0; i < rowSize; i++)
{
matrix[i]=new int[columnSize];
for (int j = 0; j < columnSize; j++)
{
matrix[i][j]=otherMatrix.matrix[i][j];
}
}
}
matrixType::~matrixType()
{
delete [] matrix;
}
int main()
{
matrixType a(2,2);
matrixType b(2,2);
matrixType c(0,0);
cout << "fill matrix a:"<< endl;;
a.fillMatrix();
cout << "fill matrix b:"<< endl;;
b.fillMatrix();
cout << a;
cout << b;
//c = a+b;
cout <<"matrix a + matrix b =" << a+b;
system("PAUSE");
return 0;
}
EDIT:
still having trouble with things not returning what i am telling it to return
This code doesn't do what you think it does:
for (int j = 0; j < columnSize; j++)
{
matrix[i]=new int[columnSize];
matrix[i][j]=otherMatrix.matrix[i][j];
}
It allocates a column, then copies the first value. Then it allocates another column (forgetting about the old column), and copies the second value. Then it allocates another column (forgetting about the old column again), and copies the third value.
I hope the problem is clear from that description alone.
Are you trying to use matrixType c();? That would declare a function. The correct syntax to use the default constructor would be matrixType c;
Your operator= doesn't actually assign anything. So c = a+b; calculates a+b but doesn't change c.
I am trying to take in an input for the dimensions of a 2D matrix. And then use user input to fill in this matrix. The way I tried doing this is via vectors (vectors of vectors). But I have encountered some errors whenever I try to read in data and append it to the matrix.
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
for(int j = 0; j<CC; j++)
{
cout<<"Enter the number for Matrix 1";
cin>>matrix[i][j];
}
}
Whenever I try to do this, it gives me a subscript out of range error. Any advice?
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR size CC vectors, filled with 0.
As it is, both dimensions of your vector are 0.
Instead, initialize the vector as this:
vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
matrix[i].resize(CC);
This will give you a matrix of dimensions RR * CC with all elements set to 0.
I'm not familiar with c++, but a quick look at the documentation suggests that this should work:
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
vector<int> myvector;
for(int j = 0; j<CC; j++)
{
int tempVal = 0;
cout<<"Enter the number for Matrix 1";
cin>>tempVal;
myvector.push_back(tempVal);
}
matrix.push_back(myvector);
}
Assume we have the following class:
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> data;
};
First of all I would like suggest you to implement a default constructor:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
private:
std::vector<std::vector<int>> data;
};
At this time we can create Matrix instance as follows:
Matrix one;
The next strategic step is to implement a Reset method, which takes two integer parameters that specify the new number of rows and columns of the matrix, respectively:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
if (rows == 0 || cols == 0) {
data.assign(0, std::vector<int>(0));
} else {
data.assign(rows, std::vector<int>(cols));
}
}
private:
std::vector<std::vector<int>> data;
};
At this time the Reset method changes the dimensions of the 2D-matrix to the given ones and resets all its elements. Let me show you a bit later why we may need this.
Well, we can create and initialize our matrix:
Matrix two(3, 5);
Lets add info methods for our matrix:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
At this time we can get some trivial matrix debug info:
#include <iostream>
void MatrixInfo(const Matrix& m) {
std::cout << "{ \"rows\": " << m.GetNumRows()
<< ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}
int main() {
Matrix three(3, 4);
MatrixInfo(three);
}
The second class method we need at this time is At. A sort of getter for our private data:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int At(const int &row, const int &col) const {
return data.at(row).at(col);
}
int& At(const int &row, const int &col) {
return data.at(row).at(col);
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
The constant At method takes the row number and column number and returns the value in the corresponding matrix cell:
#include <iostream>
int main() {
Matrix three(3, 4);
std::cout << three.At(1, 2); // 0 at this time
}
The second, non-constant At method with the same parameters returns a reference to the value in the corresponding matrix cell:
#include <iostream>
int main() {
Matrix three(3, 4);
three.At(1, 2) = 8;
std::cout << three.At(1, 2); // 8
}
Finally lets implement >> operator:
#include <iostream>
std::istream& operator>>(std::istream& stream, Matrix &matrix) {
int row = 0, col = 0;
stream >> row >> col;
matrix.Reset(row, col);
for (int r = 0; r < row; ++r) {
for (int c = 0; c < col; ++c) {
stream >> matrix.At(r, c);
}
}
return stream;
}
And test it:
#include <iostream>
int main() {
Matrix four; // An empty matrix
MatrixInfo(four);
// Example output:
//
// { "rows": 0, "cols": 0 }
std::cin >> four;
// Example input
//
// 2 3
// 4 -1 10
// 8 7 13
MatrixInfo(four);
// Example output:
//
// { "rows": 2, "cols": 3 }
}
Feel free to add out of range check. I hope this example helps you :)
try this. m = row, n = col
vector<vector<int>> matrix(m, vector<int>(n));
for(i = 0;i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link
After initialization there will be no errors, see this link
What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
Please try this out :
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}
I did this class for that purpose. it produces a variable size matrix ( expandable) when more items are added
'''
#pragma once
#include<vector>
#include<iostream>
#include<iomanip>
using namespace std;
template <class T>class Matrix
{
public:
Matrix() = default;
bool AddItem(unsigned r, unsigned c, T value)
{
if (r >= Rows_count)
{
Rows.resize(r + 1);
Rows_count = r + 1;
}
else
{
Rows.resize(Rows_count);
}
if (c >= Columns_Count )
{
for (std::vector<T>& row : Rows)
{
row.resize(c + 1);
}
Columns_Count = c + 1;
}
else
{
for (std::vector<T>& row : Rows)
{
row.resize(Columns_Count);
}
}
if (r < Rows.size())
if (c < static_cast<std::vector<T>>(Rows.at(r)).size())
{
(Rows.at(r)).at(c) = value;
}
else
{
cout << Rows.at(r).size() << " greater than " << c << endl;
}
else
cout << "ERROR" << endl;
return true;
}
void Show()
{
std::cout << "*****************"<<std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " <<setw(5)<< c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
void Show(size_t n)
{
std::cout << "*****************" << std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " << setw(n) << c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
// ~Matrix();
public:
std::vector<std::vector<T>> Rows;
unsigned Rows_count;
unsigned Columns_Count;
};
'''