Merging two arrays with a defined range

Given two vectors
- first vector nums1 = {1,2,3,0,0,0};
- second vector nums 2 = {4,5,6};

say if i want to merge only part of nums1 with all of num2,
i.e. result vector = {1,2,3,4,5,6}

is there an easier way for me to re-write just nums1.end()?

and not having to use slice & back_inserter?
or remove the last three elements of nums1 before adding nums2?


Apologies that my fundamentals are not strong, and i get overwhelmed and confused as i google different resources to try to understand...


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
58
  #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()
{
    // Get the vector
    
    // here i inputed the nums1 nums2 arrays directly as vector
    // by right, i should write code to pass the values. nvm
    
    // https://leetcode.com/problems/merge-sorted-array/
    // for the original challenge 
    
   vector<int> nums1 = {1,2,3,0,0,0};    		// m = 3
   vector<int> nums2 = {4,5,6};				// n = 3
   
   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.end(),         // how should i modify this line ?
                   nums2.begin(),
                   nums2.end(),
                   vect_any.begin());
 	
    
    cout<<"New Vector Elements using 'merge()': ";
    print_vector(vect_any);
 
    return 0;
}
Last edited on
1
2
3
4
5
    merge( nums1.begin(),
           nums1.begin() + m,
           nums2.begin(),
           nums2.begin() + n,
           vect_any.begin() );
merge(...) does more than just appending it also sorts the data.

Howerver you can easily merge just part of the data, like so:
1
2
3
4
5
    merge(         nums1.begin(),
                   nums1.begin() + m,         // Note
                   nums2.begin(),
                   nums2.begin() + n,         // Note
                   vect_any.begin());
an iterator like .begin() can have numbers added/subtracted similar to adding/subtracting numbers from pointers - if the iterator supports addition/subtraction. There are also std::next(), std::prev() which will return an adjusted iterator. See http://www.cplusplus.com/reference/iterator/ for info and what can be done with what type of iterator.

merge() requires that the input ranges are already sorted
http://www.cplusplus.com/reference/algorithm/merge/

There is also ranges::merge() from C++20:
https://en.cppreference.com/w/cpp/algorithm/ranges/merge
Last edited on
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;
}




From the spec:

The elements are compared using operator<


Hence the output is determined by the result of this operation on the input ranges - hence the requirement for the input ranges to be sorted.

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
#include <iostream>
#include <vector>
#include <algorithm>

void print_vector(const std::vector<int>& vector_any) {
	for (const auto& v : vector_any)
		std::cout << v << ' ';

	std::cout << "\n";
}

int main() {
	const std::vector<int> nums1 {3, 2, 1, 0, 0, 0}; 	// here i reversed the inputs to try
	const std::vector<int> nums2 {6, 5, 4};				// reversed inputs too

	std::cout << "First Vector Elements - nums1: ";
	print_vector(nums1);

	std::cout << "Second Vector Elements - nums2: ";
	print_vector(nums2);

	constexpr size_t m{3}, n{3};

	//Declaring the new vector to store elements from both vectors
	std::vector<int> vect_any(m + n);

	std::merge(nums1.begin(),
		nums1.begin() + m,
		nums2.begin(),
		nums2.begin() + n,
		vect_any.begin());

	std::cout << "New Vector Elements using 'merge()': ";
	print_vector(vect_any);
}



First Vector Elements - nums1: 3 2 1 0 0 0
Second Vector Elements - nums2: 6 5 4
New Vector Elements using 'merge()': 3 2 1 6 5 4


The results isn't really 'merged', but appended!

If nums1 is changed to 7, 2, 1, 0, 0, 0 then the output becomes:


First Vector Elements - nums1: 7 2 1 0 0 0
Second Vector Elements - nums2: 6 5 4
New Vector Elements using 'merge()': 6 5 4 7 2 1


with the ordering of the append reversed!
Last edited on
@memepapa,
Just put
1
2
    sort( nums1.begin(), nums1.begin()+m );
    sort( nums2.begin(), nums2.begin()+n );

before your merge call.

std::merge doesn't do any sorting. It assumes that the relevant input sequences are already sorted.
remove the last three elements of nums1 before adding nums2?


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
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void print_vector(string label, vector<int>& v)
{
    cout << label << '\n';
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << ' ';
    }
    cout <<  "\n\n";
}

int main()
{
    vector<int> nums1 = {1,2,3,0,0,0};  // m = 3
    vector<int> nums2 = {4,5,6};
    
    print_vector("nums1 - original", nums1);
    print_vector("nums2 - original", nums2);
    
    int m = 3;
    
    nums1.resize(m);
    print_vector("nums1 - resized", nums1);
    
    for (int i = 0; i < nums2.size(); i++)
    {
        nums1.push_back(nums2[i]);
    }
    print_vector("nums1 - updated", nums1);
    
    return 0;
}



nums1 - original
1 2 3 0 0 0

nums2 - original
4 5 6

nums1 - resized
1 2 3

nums1 - updated
1 2 3 4 5 6

Program ended with exit code: 0


If it's done by appending, then possibly which then sorts the final vector:

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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void print_vector(const std::string& label, const std::vector<int>& v) {
	std::cout << label << '\n';

	for (const auto& n : v)
		std::cout << n << ' ';

	std::cout << "\n\n";
}

int main() {
	std::vector<int> nums1 {1, 2, 3, 0, 0, 0};  // m = 3
	std::vector<int> nums2 {4, 5, 6};

	print_vector("nums1 - original", nums1);
	print_vector("nums2 - original", nums2);

	constexpr size_t m {3};

	nums1.resize(m);
	print_vector("nums1 - resized", nums1);

	nums1.insert(nums1.end(), nums2.begin(), nums2.end());
	print_vector("nums1 - updated", nums1);

	std::sort(nums1.begin(), nums1.end());
	print_vector("Nums1 - sorted", nums1);
}

Topic archived. No new replies allowed.