This C++ Program which combines two sorted arrays. The program uses two user-defined functions enter_elem( ) and comb( ). The function enter_elem( ) takes number of elements of the vector as the input and runs a for loop to push elements into the vector. The vectors are then sorted and passed into the function comb( ) which returns a combined vector. The elements of the combined vector are then output to the standard output stream.
Here is source code of the C++ program which combines two sorted arrays. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Combine two Sorted Arrays
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
/* Function to input vector elements */
void enter_elem(vector<int>& a)
{
int alen, val;
cout << "Enter number of elements : ";
cin >> alen;
for (int i = 0; i < alen; i++)
{
cin >> val;
a.push_back(val);
}
}
/* Function to combine two integer vectors */
vector<int> comb(vector<int> a, vector<int> b)
{
int alen = a.size();
int blen = b.size();
int tlen = alen + blen;
vector<int> c(tlen);
int i = 0, j = 0, k = 0;
while (i < alen && j < blen)
{
if (a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
while (i < alen)
c[k++] = a[i++];
while (j < blen)
c[k++] = b[j++];
return c;
}
int main()
{
vector<int> a;
vector<int> b;
cout << "Initialising vector A" << endl;
enter_elem(a);
sort(a.begin(), a.end());
cout << "Initialising vector B" << endl;
enter_elem(b);
sort(b.begin(), b.end());
vector<int> c = comb(a, b);
for (int i = 0; i < c.size(); i++)
cout << c[i] << " ";
cout << endl;
}
$ g++ main.cpp $ ./a.out Initialising vector A Enter number of elements : 5 3 1 5 3 7 Initialising vector B Enter number of elements : 3 8 5 10 1 3 3 5 5 7 8 10
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Computer Science Books
- Buy Programming Books
- Practice Computer Science MCQs
- Buy C++ Books
- Apply for Computer Science Internship