thanks for helping me, lastchance, coder777 and seeplus
i have further questions regarding these two:
a) merge(...) does more than just appending it also sorts the data.
b) merge() requires that the input ranges are already sorted
I read the links that seeplus posted (thanks)
note that i didn't include
std::sort (...)
in my revised code (below)
and I observed that
1) the merging still works if I don't sort them first
2) sorting doesn't happen automatically.
am I right that std::sort (...) is not compulsory and I do not have to sort the vector first before using merge() ?
my input after revision are
nums1: 3 2 1 0 0 0
nums2: 6 5 4
and the output is 3 2 1 6 5 4
(i was sort of expecting it to be re-arranged to 1 2 3 4 5 6
but apparently my expectations were wrong?
here's my revised code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
//Function to print vector
void print_vector(vector<int> vector_any)
{
for (int i = 0; i < vector_any.size(); i++)
{
cout << vector_any[i] << " ";
}
cout << "\n";
}
int main()
{
vector<int> nums1 = {3,2,1,0,0,0}; // here i reversed the inputs to try
vector<int> nums2 = {6,5,4}; // reversed inputs too
cout<<"First Vector Elements - nums1:";
print_vector(nums1);
cout<< "Second Vector Elements - nums2: ";
print_vector(nums2);
int m=3, n=3;
//Declaring the new vector to store elements from both vectors
// vector<int> vect_any(first.size() + second.size());
vector<int> vect_any(m + n);
merge( nums1.begin(),
nums1.begin()+m,
nums2.begin(),
nums2.end(),
vect_any.begin());
cout<<"New Vector Elements using 'merge()': ";
print_vector(vect_any);
return 0;
}
|