In this exercise you are invited to write a program in C++ that performs a horiz
ID: 3776919 • Letter: I
Question
In this exercise you are invited to write a program in C++ that performs a horizontal concatenation of two n*m matrices:
Example: n =3, m = 5
Matrix a :
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Matrix b :
16 17 18 19 20
6 7 8 9 10
11 12 13 14 15
Horizontal Concatenation Matrix:
1 2 3 4 5 16 17 18 19 20
6 7 8 9 10 6 7 8 9 10 11 12 13 14 15 11 12 13 14 15
Your program should create two functions:
concatenate() that takes 2 vectors as parameters and return an array containing the two vectors
Example: for m =5
Vector a: 1 2 3 4 5
Vector b: 6 7 8 9 10
Concatenated array: 1 2 3 4 5 6 7 8 9 10
horizontalConcatenation() that takes two matrices as parameters and returns a matrix representing their concatenation. This function should use the concatenate () functionIn this exercise you are invited to write a program that performs a horizontal concatenation of two n*m matrices:
Example: n =3, m = 5
Matrix a :
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Matrix b :
16 17 18 19 20
6 7 8 9 10
11 12 13 14 15
Horizontal Concatenation Matrix:
1 2 3 4 5 16 17 18 19 20
6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15
Your program should create two functions:
concatenate() that takes 2 vectors as parameters and return an array containing the two vectors
Example: for m =5
Vector a: 1 2 3 4 5
Vector b: 6 7 8 9 10
Concatenated array: 1 2 3 4 5 6 7 8 9 10
horizontalConcatenation() that takes two matrices as parameters and returns a matrix representing their concatenation. This function should use the concatenate () function
Explanation / Answer
The following program is your required one.
#include<iostream>
#include<vector>
using namespace std;
void concatenate(vector<int> &v1, vector<int> &v2, int *a)
{
int i=0;
vector<int> tmp(v1.begin(),v1.end());
tmp.insert(tmp.end(),v2.begin(),v2.end());
for(vector<int>::iterator itr1=tmp.begin();itr1!=tmp.end();itr1++)
a[i++]=*itr1;
}
void horizontalConcatenation(int **a,int **b,int n,int m, int **newArr)
{
vector<int>v1,v2;
for(int i=0;i<n;i++)
{
v1.clear();v2.clear();
for(int j=0;j<m;j++)
{
v1.push_back(a[i][j]);
v2.push_back(b[i][j]);
}
newArr[i]= new int[m+m];
concatenate(v1,v2,newArr[i]);
}
}
void read(int **a,int n,int m)
{
for(int i=0;i<n;i++)
{
a[i]=new int[m];
for(int j=0;j<m;j++)
cin>>a[i][j];
}
}
void print(int **a,int n,int m)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
int main(void)
{
int n,m;
int **a,**b,**c;
cout<<"Enter n,m:";
cin>>n>>m;
a=new int*[n];
b=new int*[n];
c=new int*[n];
cout<<"Input matrix A row wise:"<<endl;
read(a,n,m);
print(a,n,m);
cout<<"Input matrix B row wise:"<<endl;
read(b,n,m);
print(b,n,m);
horizontalConcatenation(a,b,n,m,c);
print(c,n,m+m);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.