Users Online
· Guests Online: 98
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
C++ Program to Merge Two Sorted Vectors
C++ Program to Merge Two Sorted Vectors
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
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.