My program is about taking the transpose of a matrix and displaying it, using structs. I'm using pointer to structs in each function, just for practice although I could've done it by simply passing the struct or by reference. The program is working fine until function inputMatrix. The program takes input and then finishes executing without any output.
What I know for sure is the problem is in display function or structure trans I'm creating in main(which has the final result).
My code is below:
#include <iostream>
#include <iomanip>
using namespace std;
struct Matrix
{
int **data;
int rows;
int columns;
};
void createMatrix(Matrix *mat)
{
mat->data = new int *[mat->rows];
for (int i = 0; i < mat->columns; i++)
{
mat->data[i] = new int[mat->columns];
}
}
void inputMatrix(Matrix *mat)
{
for (int i = 0; i < mat->rows; i++)
{
for (int j = 0; j < mat->columns; j++)
{
cout << "Enter element of row " << i + 1 << " and column " << j + 1<<endl;
cin >> mat->data[i][j];
}
}
}
Matrix transpose(Matrix* mat)
{
Matrix transpose;
transpose.rows = mat->rows;
transpose.columns = mat->columns;
for (int i = 0; i < mat->rows;i++)
{
for(int j = 0;j<mat->columns;j++)
{
transpose.data[i][j] = mat->data[j][i];
}
}
return transpose;
}
void display(Matrix* mat)
{
for(int i = 0;i<mat->rows;i++)
{
for(int j = 0;j<mat->columns;j++)
{
cout<<setw(3)<<mat->data[i][j];
}
cout<<endl;
}
}
int main()
{
Matrix mat;
cout<<"Enter the rows of matrix: \n";
cin>>mat.rows;
cout<<"\nEnter the columns of matrix: \n";
cin>>mat.columns;
createMatrix(&mat);
inputMatrix(&mat);
cout<<endl;
Matrix trans = transpose(&mat);
display(&trans);
return 0;
}
The problem was in function transpose, I needed to allocate memory to Matrix transpose
The code is below:
Matrix transpose(Matrix* mat)
{
Matrix transpose;
transpose.rows = mat->rows;
transpose.columns = mat->columns;
createMatrix(&transpose);
for (int i = 0; i < mat->columns;i++)
{
for(int j = 0;j<mat->rows;j++)
{
transpose.data[i][j] = mat->data[j][i];
}
}
return transpose;
}
Related
I have a constructor and a method in an implementation file:
Boggle::Boggle(std::string boardString){
dim = sqrt(boardString.size());
vector<vector<char> > grid(dim, vector<char>(dim));
int co = 0;
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
grid[i][j] = boardString[co];
co++;
}
}
}
void Boggle::printMe() {
for (auto inner : grid)
{
for (auto item : inner)
{
cout << item << " ";
}
cout << endl;
}
}
The program executes, but doesn't do anything. As you can see I have sized my vector when I declared it. I believe the issue lies in my logic of assigning a character to a vector from a string perhaps.
As hinted in comments your vector grid is local to your function. You mostly likely wanted to use a class variable but ended up creating a local variable. You can use resize to set the dimensions of your grid. Also its better to ceil the sqrt to make sure that we are not missing any characters.
Example:
#include <stdio.h>
#include <vector>
#include <string>
#include <cmath>
#include <iostream>
using namespace std; // Avoid this
class Boggle{
public:
int dim;
vector<vector<char>> grid;
Boggle(string boardString);
void printMe();
};
Boggle::Boggle (std::string boardString)
{
dim = ceil(sqrt(boardString.size ()));
grid.resize(dim, vector <char>(dim));
int co = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++)
{
grid[i][j] = boardString[co];
co++;
}
}
}
void Boggle::printMe ()
{
for (auto inner:grid) {
for (auto item:inner)
{
cout << item << " ";
}
cout << endl;
}
}
int main(){
Boggle boggle("hello world");
boggle.printMe();
return 0;
}
Result:
h e l l
o w o
r l d
I want to declare two dimensional array with variable size.
I wrote the following code but something goes wrong!
int **p2DArray;
p2DArray = new int*[target_counter_new];
for (int i = 0; i < target_counter_new; ++i)
{
p2DArray[i] = new int[target_counter_old];
}
for(int i_oghli=0;i_oghli<target_counter_new;i_oghli++)
for(int j_oghli=0;j_oghli<target_counter_old;j_oghli++)
{
p2DArray[i_oghli][j_oghli]=i_oghli+10;
cout<<p2DArray[i_oghli][j_oghli];
}
what is problem here ?
#include <iostream>
using namespace std;
const int target_counter_new = 4;
const int target_counter_old = 4;
int main() {
int **p2DArray;
p2DArray = new int*[target_counter_new];
for (int i = 0; i < target_counter_new; ++i) {
p2DArray[i] = new int[target_counter_old];
}
for(int i_oghli=0;i_oghli<target_counter_new;i_oghli++) {
for(int j_oghli=0;j_oghli<target_counter_old;j_oghli++) {
p2DArray[i_oghli][j_oghli]=i_oghli+10;
cout<<p2DArray[i_oghli][j_oghli] << " ";
}
cout << endl;
}
// don't forget to delete the array
for (int i = 0 ; i < target_counter_new; ++i) {
delete [] p2DArray[i];
}
delete [] p2DArray;
return 0;
}
Check here : code
There doesn't appear to be any problem.
I have created a 3d array into main function because one of its size came from used input. I am using C++
std::cin >> size;
typedef int T[8][3];
T* tables = new T[size];
It is basically tables[size][8][3]
Now I have to use this 3d table in different functions and have to store values into it. The best way to do it by make this table as a global variable. But I am not sure that I can do it after main function. The other option I have, that I have to pass this table as a parameter and have to return that at the end of the function.
I have tried both the approach but I am having error. Please help me about this issue. I don't know which approach to choose and how to do it.
Thank you in advance.
**Example:**This an example what I really want to do. Here I create a 3d array in main function and through another function I gave some input into that array and again print that in main function.
#include <iostream>
#include <conio.h>
using namespace std;
class M
{
public:
int i,j,k;
public:
int pass(int (*table)[8][3],int size);
}
int M:: pass(int (*table)[8][3],int s)
{
for (i=0;i<s;i++)
{
//int a = tables[i][2][1];
for(j=0;j<8;j++)
{
for(k=0;k<3;k++)
{
table[i][j][k]=i;
}
}
}
return (*table)[8][3]; // not sure about this
}
int main()
{
int size,i,j,k;
std::cin >> size;
typedef int T[8][3]; // T is your 2d array type
T* tables = new T[size];
cout << "test";
M mx;
mx.pass(tables,size); // not sure
for (i=0;i<size;i++)
{
for(j=0;j<8;j++)
{
for(k=0;k<3;k++)
{
cout<<tables[i][j][k];
cout<<" ";
}
cout<<endl;
}
cout<<endl;
cout<<"..........." << i <<endl;
}
getch();
}
I don't know if I completely understand your problem. But you can definitely store the pointer locally in your object and reference it elsewhere. Something like this:
class M
{
public:
M(int(*tbl)[8][3]) : table(tbl) { }
int(*table)[8][3];
int i, j, k;
public:
void pass(int size);
};
void M::pass(int s)
{
for (i = 0; i<s; i++)
{
for (j = 0; j<8; j++)
{
for (k = 0; k<3; k++)
{
table[i][j][k] = i;
}
}
}
}
int main()
{
int size, i, j, k;
std::cin >> size;
typedef int T[8][3]; // T is your 2d array type
T* tables = new T[size];
cout << "test";
M mx(tables);
mx.pass(size); // not sure
for (i = 0; i<size; i++)
{
for (j = 0; j<8; j++)
{
for (k = 0; k<3; k++)
{
cout << tables[i][j][k];
// or you can also:
// cout << mx.table[i][j][k];
cout << " ";
}
cout << endl;
}
cout << endl;
cout << "..........." << i << endl;
}
_getch();
}
Since you are creating a dynamic 3D array whose two dimensions are fixed, Use a std::array<std::array<int, 3>, 8> as your 2D array. Use a std::vector<__2D_ARRAY_TYPE> to create the 3D array.
#include <iostream>
#include <array>
#include <vector>
int main() {
std::array<std::array<int, 3>, 8> array_2d ;
std::vector<decltype(array_2d)> array_3d ;
int size = 4 ;
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < 8; ++j)
for(int k = 0; k < 3; ++k)
array_2d[j][k] = j + k ;
array_3d.push_back(array_2d);
}
return 0;
}
Something like this you can use easily which does the job more easily without any manual memory management.
You can pass it to a function. The signature would be :
return_type function_name(const std::vector<std::array<std::array<int, 3>, 8>>& array_3d)
{ .... }
In
class M
{
public:
int i,j,k;
public:
int pass(int (*table)[8][3],int size);
}
you don't have to write public twice. You can simply put all of the public member data under the keyword public.
Also, you seem to be re-writing your function over again at the very end. Instead of
cout<<tables[i][j][k];
You can write
cout<<*tables
I have an assignment where i need to use a matrix class of type T elements. I have a constructor using 2 int, one copy constructor, one constructor using a string and a destructor. matrix A uses first constructor and works fine, matrix B uses second and also prints out fine but i have an issue with matrix C. If I a declare it by itself(removing matrix a and b from main) it prints as well, but when all is there, it prints out something like:
3735748 3745176
3745176 3735748
(instead of
5 6
7 8)
And numbers change everytime I compile.
I feel like this should be obvious but i'm a beginner and cant figure it out.. Any help welcome! Thank you
template <class T>
class matrice
{
private :
unsigned int nLignes; //number of rows
unsigned int nColonnes; //nbr of cols
T** rep;
public :
matrice( unsigned int nl, unsigned int nc)
{
setLignes(nl);
setColonnes(nc);
rep = new T*[nl];
for(int i = 0; i < nl; i++){
rep[i] = new T[nc];
}
for(int i = 0; i < nl; i++){
for(int j = 0; j < nc; j++){
rep[i][j] = (T) i*j;
}
}
}
matrice( const matrice& mat)// my copy constructor
{
setLignes(mat.nLignes);
setColonnes(mat.nColonnes);
rep = new T*[nLignes];
for(int i = 0; i < nLignes; i++){
rep[i] = new T[nColonnes];
}
for(int i = 0; i < nLignes; i++){
for(int j = 0; j < nColonnes; j++){
rep[i][j] = (T) i*j;
}
}
}
matrice( const std::string& UnString)//constructor using a string
//"nl,nc,val1, val2.."
{
std::vector<int> vect;
std::stringstream ss(UnString);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
setLignes(vect.at(0));
setColonnes(vect.at(1));
int taille = nLignes * nColonnes;
vect.erase(vect.begin(), vect.begin()+2);
if(taille == vect.size()){ // making sure enough values to
//fill array
int n = 0;
for(int i = 0; i < nLignes; i++){
rep[i] = new T[nColonnes];
}
for(int i = 0; i < nLignes; i++){
for(int j = 0; j < nColonnes; j++){
rep[i][j] = vect.at(n);
n++;
}
}
}
}
~matrice()
{
delete[] rep;
}
void afficher();//printing function
void setLignes(int l)
{
nLignes = l;
}
void setColonnes(int c)
{
nColonnes = c;
}
};
template <class T>
void matrice<T>::afficher()//printing function
{
int i,j;
for (i=0;i < nLignes;i++)
{
for(j=0;j < nColonnes;j++)
{
cout << rep[i][j] << " ";
}
cout << "\n";
}
}
/*
*
*MAIN*
******/
int main(int argc, char *argv[])
{
matrice <unsigned int> mat(5,3);//MATRIX A
matrice <unsigned int> a = mat;
a.afficher();
{
matrice <unsigned int> mat(6,6);//MATRIX B
matrice <unsigned int> b = mat;
b.afficher();
}
matrice <unsigned int> c("2,2,5,6,7,8");//MATRIX C !! problem
c.afficher();
system("pause");
return 0;
}
You forget allocate space for rep in the constructor using a string.
Moreover, your deconstructor is at risk of memory leaking, please check it yourself.
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;
};
'''