How to set a matrix as a parameter to a function - c++

I have an matris that the user will define it's size and it's elemant's value, i want to send it into a function from main as parameter or someway else, tried to use pointer for it but couldn't be successful, defining it as global is not a solution because the value i will give to matris' size is not set until the user enters. A matris can't be a functions parameter as well, so I'm stuck. Anyone can help me to send that matris to the function. - sorry for long question..
int main(){
int matris [k][k];
for(i=0 ; i<k ; i++){
for(t=0 ; t<k ; t++){
cin<<matris[i][t];
}
}
func(a,b,c,x);
}
func(int a, int b, int c, x){
//some stuff
}
That's in sum how the code looks like, i know using'x' like that is impossible, i am kinda trying to change the x with the matris value, but we are unable to set a matris as a parameter.

You can represent the matrix as a vector<vector<int> >. Try something like this:
#include <vector>
using namespace std;
void myFunction(const vector<vector<int> >& matrix) {
// do something w/ matrix passed in...
}
int main() {
// create a 3x4 matrix initialized to all zero
const size_t rowCount = 3;
const size_t colCount = 4;
vector<vector<int> > matrix(rowCount, vector<int>(colCount, 0));
// pass matrix to a function
myFunction(matrix);
return 0;
}

#include <iostream>
using namespace std;
int const k = 2;
void func( int (&m)[k][k] )
{
//some stuff
cout << "func!\n";
}
int main()
{
int matris[k][k];
for(int i=0 ; i<k ; i++)
{
for(int t=0 ; t<k ; t++)
{
//cin >> matris[i][t];
}
}
func( matris );
}

Related

Is it possible to pass an array into a vector in C++

Please find my below code.I want to know whether we can pass an array through a function which is accepting vector. If yes please tell me how.
int main()
{
int N,M,i;
cin>>N>>M;
int fs[N];
for(i=0;i<N;i++){
cin>>fs[i];
}
int K=findK(fs,M);
cout << "Hello World!" << endl;
return 0;
}
int findK(????,int M){
int b_sz,no_b;
int tfs[]=fs;
make_heap(tfs);
I've made some modifications to your code to help you get started. Furthermore, I recommend taking a look at http://www.cplusplus.com/reference/vector/vector/ for a high-level overview of std::vector and the functionalities it provides.
#include <iostream>
#include <vector>
using namespace std;
int findK(const vector<int> &fs, int M); // Function stub so main() can find this function
int main()
{
int N, M, i; // I'd recommend using clearer variable names
cin >> N >> M;
vector<int> fs;
// Read and add N ints to vector fs
for(i = 0; i < N; i++){
int temp;
cin >> temp;
fs.push_back(temp);
}
int K = findK(nums, M);
cout << "Hello World!" << endl;
return 0;
}
int findK(const vector<int> &fs, int M){ // If you alter fs in make_heap(), remove 'const'
make_heap(fs);
// int b_sz,no_b; // Not sure what these are for...
// int tfs[]=fs; // No need to copy to an array
// make_heap(tfs); // Per above, just pass the vector in

Matrix - return and pass as parameter c++

I'm trying to use clear functions to do a matrix multiplication with random generated values. Therefore I'm hoping to use a function(mat_def) to generate the matrices and another function(mat_mul) to multiply them when the matrices are sent as parameters.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
double mat_def(int n) //how to return the matrix
{
double a[n][n];
double f;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
f= rand();
cout<<f ;
a[i][j]=f;
}
}
return 0;
}
double mat_mul( int n, double a[n][n], double b[n][n]) //how to send matrix as parameter
{
return 0;
}
int main()
{
/* initialize random seed: */
srand (time(NULL));
mat_def(10);
}
Here's a nice, standard C++ Matrix template for you.
Matrix.h
#include <vector>
class Matrix
{
class InnerM
{
private:
int ydim;
double* values;
public:
InnerM(int y) : ydim(y)
{
values = new double[y];
}
double& operator[](int y)
{
return values[y];
}
};
private:
int xdim;
int ydim;
std::vector<InnerM> inner;
public:
Matrix(int x, int y) : xdim(x), ydim(y), inner(xdim, InnerM(ydim))
{
}
InnerM& operator[](int x)
{
return inner[x];
}
};
All the memory leaks are there for you but you get the idea. From here you can handle the multiplication by overiding ::operator*() in the Matrix class.
I assume your problem is to define 2-D array and then pass it to mat_mul function to multiply the matrices. And the rest will be quite simple.
Defining the 2-D array(considering memory needs are known at run time):
int rows,cols;
cin >> rows;
cin >> cols;
int **arr = new int*[rows]; // rows X cols 2D-array
for(int i = 0; i < rows; ++i) {
arr[i] = new int[cols];
}
You can define another 2-D array exactly the same way with required rows and column.
now, Passing the 2-D array to function:
void mat_mul(int **arr1, int **arr2, int m, int n, int p, int q){
//define a 2-D array to store the result
//do the multiplication operation
//you could store the result in one of the two arrays
//so that you don't have to return it
//or else the return type should be modified to return the 2-D array
}
example:
void display(int **arr, int row, int col){
for (int i=0; i<row; i++){
for(int j=0;j<col; j++){
cout << arr[i][j] << '\t';
}
cout << endl;
}
}
Delete the memory if not required anymore with the following syntax:
for(int i=0; i<rows; i++){
delete[] array[i];
}
delete[] array;
hope this will be sufficient to get your work done!
there is already an answer on how to return a 2-D array on SO. Check the link below.
https://stackoverflow.com/a/8618617/8038009
Returning the raw allocation is a sucker bet. You need to manage all of the memory allocated yourself and pass it around with the matrix size parameters.
Why suffer? Use a matrix class
template<class Type>
class Matrix{
int rows;
int cols;
std::vector<type> data;
public:
Matrix(int row, int col):rows(row), cols(col), data(rows*cols)
{
// does nothing. All of the heavy lifting was in the initializer
}
// std::vector eliminates the need for destructor, assignment operators, and copy
//and move constructors.
//add a convenience method for easy access to the vector
type & operator()(size_t row, size_t col)
{
return data[row*cols+col];
}
type operator()(size_t row, size_t col) const
{
return data[row*cols+col];
}
};
Usage would be
Matrix<double> mat_mul(const Matrix<double> &a, const Matrix<double> &b)
{
Matrix<double> result;
// do multiplication
return result;
}
int main()
{
/* initialize random seed: */
srand (time(NULL));
Matrix<double> matA(10, 10);
matA(0,0) = 3.14; // sample assignment
matA(9,9) = 2.78;
double x = matA(0,0) * matA(9,9)
Matrix<double> matB(10, 10);
Matrix<double> matC = mat_mul(matA, matB) ;
}
More functionality, such as construction from an initializer list, can be added to the class to make your life easier. You can also specify an operator * overload for Matrix and use that in place of mat_mul if you chose. Read Operator overloading for more on that option.

How to pass two-dimensional array to the function so that code would compile

I'm trying to make a program which fill a quadratic matrix with some random values. So here the source code (which works fine):
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
int const n = 5;
int matrix[n][n];
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
matrix[i][j] = rand()%10; // fill matrix
cout<<setw(2)<<matrix[i][j]; // matrix output
}
cout<<"\n"; // new line
}
}
But now I want to rewrite this code using my own function:
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
void fillAndPrintArray (int **matrix, int n); // function prototype
int main()
{
int const n = 5;
int matrix[n][n];
fillAndPrintArray(matrix, n);
}
void fillAndPrintArray(int **matrix, int n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
matrix[i][j] = rand()%10; // fill matrix
cout<<setw(2)<<matrix[i][j];
}
cout<<"\n"; // new line
}
}
But I can't compile this code. I'm getting error:
||In function 'int main()':error: cannot convert 'int (*)[5]' to 'int**' for argument '1' to 'void fillAndPrintArray(int**, int)'.
I don't know how to fix this.
The problem is that you are passing a multidimensional array to a function that takes a pointer to a pointer. In regards to arrays this is a pointer to the first element of an array of pointers, not a two dimensional array.
If you want to pass multidimensional array to a function you can use a template function and take the array by reference.
template<std::size_t U, std::size_t V>
void func(const int (&arr)[U][V])
{
// do stuff
}
int main()
{
int arr1[10][10];
int arr2[15][10];
func(arr1);
func(arr2);
}
To do this without a template function just replace U and V with the desired dimensions. for instance to pass a 5x5 array as in your question you would do this.
void func(const int(&arr)[5][5])
{
}

Passing a 2 dimensional vector in Class OOP

I am confused about passing a 2D vector using OOP
For example:
class ABC
{
public:
void function()
{
vector<vector<string>> high;
for ( int i=0; i<100; i++ )
{
high[0].push_back(i);
}
}
};
int main() {};
In the function , I do some calculations and the results are stored in 2D-array (high). I need the whole 2-d array to pass to the main function, How can i do it ?
I tried this,
class ABC{
public:
vector<vector<string>> function ()
{
vector<vector<string>> high;
for ( int i=0; i<100; i++ )
{
high[0].push_back(i);
}
}
};
int main()
{
ABC abc;
abc.function();
};
But it seems to be a total failure.
Thanks
You need to return your array from function like:
vector<vector<string>> function ()
{
vector<vector<string>> high;
high.resize(1); // <-- note this resize, because you are using high[0]
// element later
for ( int i=0; i<100; i++ )
{
high[0].push_back("some data...");
}
return high; // <-- note this return statement
}
Call function from main to get your data like this:
vector<vector<string>> data = function();
Other, but more efficient solution would be create your array in main and pass it by non-const reference to function:
class ABC{
public:
void function (vector<vector<string>>& high)
{
high.resize(1);
for ( int i=0; i<100; i++ )
{
high[0].push_back("some data...");
}
}
};
int main()
{
ABC abc;
vector<vector<string>> high;
abc.function(high);
};
Also make sure your vector contains elements you want to access. For example high[0] accesses first vector element. Use resize to change size. Note, that push_back automatically increases size.
for(int i = 0; i < 100; i++)
for(int j = 0; j < 100; j++)
//high[i].[j]
//high.at(i).at(j)
I Think something in this way.

2 dimensions array allocation, c++

I would like to have an array int candidates[9][] where the first dimension is known (9) and the second, depends on the execution.
I found that a method to allocate the array was the following:
int *candidates[9]; /* first allocation at declaration */
for(int i=0;i<9;i++) candidates[i] = new int[6]; /* allocation at execution */
but when I use it like that, and I try to access to candidates[i][j], it doesn't work. I initialize candidate[i] with a function fun() that return and int[] of the right size, but the content of candidate[i][j] is wrong.
candidates[0] = fun();
I don't understand where I am wrong... Thank you for your help :-)
Try int *candidates[9] instead of int candidates[9][] and it should work.
Why dont you try vector template class from STL...code is more neater and comprehensive...
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arrayOfVecs[9];
//use each array to put as many elements you want, each one different
arrayOfVecs[0].push_back(1);
arrayOfVecs[1].push_back(100);
.
.
arrayOfVecs[1].push_back(22);
arrayOfVecs[0].pop_back();
arrayOfVecs[8].push_back(45);
cout<<arrayOfVecs[1][0]<<endl;//prints 100
return 0;
}
WITH ARRAY OF POINTERS
int main()
{
int* arrayOfPtrs[9];
for(int index = 0;index<9;index++)
{
int sizeOfArray = //determine the size of each array
arrayOfPtrs[index] = new int[sizeOfArray];
//initialize all to zero if you want or you can skip this loop
for(int k=0;k<sizeOfArray;k++)
arrayOfPtrs[index][k] = 0;
}
for(int index = 0;index<9;index++)
{
for(int k=0;k<6;k++)
cout<<arrayOfPtrs[index][k]<<endl;
}
return 0;
}
Try int **candidates=0; followed by candidates = new int *[9] ;.
Code:
#include <iostream>
using namespace std;
int main(void)
{
int **candidates=0;//[9]; /* first allocation at declaration */
candidates = new int *[9] ;
for(int i=0;i<9;i++) candidates[i] = new int ; /* allocation at execution */
for( i = 0 ; i < 9 ; i++ )
{
for( int j = 0 ; j < 9 ; j++ )
{
candidates[i][j]=i*j;
cout<<candidates[i][j]<<" ";
}
cout<<"\n";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}