Advertisement

merging vectors

Started by June 09, 2021 11:26 PM
23 comments, last by shubham.puri.7742 3 years, 4 months ago

@undefined Apologies for having misread the description. I have added an interleaved function at the bottom.

My bad too. I was thinking that this would work, but apparently not:

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{
	vector<int> a = { 1,2,3 };
	vector<int> b = { 4,5,6 };
	vector<int> c(a.size() + b.size());

	merge(a.begin(), a.end(), b.begin(), b.end(), c.begin());

	for (size_t i = 0; i < c.size(); i++)
		cout << c[i] << endl;

	return 0;
}
Advertisement

@taby Merge from the algorithm header does the ‘merge’ part of ‘merge sort’, i.e. it merges in a sequence. It does not interleave in the sense that the elements alternate between elements of vectors a and b (until you get to a point where you just have to dump the surplus elements in one vector).

However, merge sort was certainly my inspiration behind the interleaved merge, because the general procedure is very similar to how you merge when merge sorting:

  1. As long as there are elements in both arrays, compare the elements currently being read and add (assuming ascending order) the lesser of the two.
  2. When one array is out of elements, dump the remaining items of the other array.

@pbivens67 Also, although it's not related to the merge algorithm, I noticed that you have

cout << merge(num_a, num_b);

You can't output a vector like that unless you have defined the behaviour using operator overloading. You could replace it with a print loop, but the ‘proper’ way in this case would be to implement the functionality for the << operator. You can use this implementation with any output stream (cout is one). This prints the vector in a familiar style you may be used to if you know Python or Haskell:

/* PRINTING VECTORS
* Operator << overloaded to display a vector as
* [1, 2, 3]
* (Terminates with a newline)
*/
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
	os << "[" << vec.at(0);
	int size = vec.size();

	for (int i = 1; i < size; ++i) {
		 os << ", " << vec.at(i);
	}

	os << "]\n";
	return os;
}

I'd probably define this neat bit in any program where I'm printing a vector more than two times.

This topic is closed to new replies.

Advertisement