Skip to content

Instantly share code, notes, and snippets.

@yzchen
Last active January 9, 2019 19:51
Show Gist options
  • Select an option

  • Save yzchen/bbcb9328955703ebe88d218da60f05f4 to your computer and use it in GitHub Desktop.

Select an option

Save yzchen/bbcb9328955703ebe88d218da60f05f4 to your computer and use it in GitHub Desktop.
merge 2-d arrays(store them as 1-d vector, because it's easy to serialize)
#include <iostream>
#include <vector>
using namespace std;
#define IndexType int
void merge_local_vectors(vector<IndexType> &first, vector<IndexType> &second, int pair_size1, int pair_size2, int key1, int key2) {
int ssz1 = first.size(), ssz2 = second.size();
int i = 0, j = 0;
vector<IndexType> res;
res.reserve(ssz1 + ssz2);
cout << res.size() << endl;
auto it1 = first.begin(), it2 = second.begin();
while (i < ssz1 && j < ssz2) {
if (first[i + key1] <= second[j + key2]) {
res.insert(res.end(), it1 + i, it1 + i + pair_size1);
i += pair_size1;
} else {
res.insert(res.end(), it2 + j, it2 + j + pair_size2);
j += pair_size2;
}
cout << "size of res : " << res.size() << endl;
}
while (i < ssz1) {
res.insert(res.end(), it1 + i, it1 + i + pair_size1);
i += pair_size1;
}
while (j < ssz2) {
res.insert(res.end(), it2 + j, it2 + j + pair_size2);
j += pair_size2;
}
first.assign(res.begin(), res.end());
}
int main(int argc, char *argv[]) {
vector<IndexType> first = {12, 5, 14, 8, 16, 12, 24, 5, 30, 5};
vector<IndexType> second = {14, 5, 18, 10, 28, 12};
merge_local_vectors(first, second, 2, 2, 0, 0);
cout << "size of first : " << first.size() << endl;
for (auto vi : first) {
cout << vi << " ";
}
cout << endl;
}
/*
output :
0
size of res : 2
size of res : 4
size of res : 6
size of res : 8
size of res : 10
size of res : 12
size of res : 14
size of first : 16
12 5 14 8 14 5 16 12 18 10 24 5 28 12 30 5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment