C++ How To Merge Two Arrays
Merge Two Arrays
Copy the elements of both arrays into a new, larger array:
Example
int first[] = {1, 2, 3};
int second[] = {4, 5, 6};
int merged[6];
for (int i = 0; i < 3; i++) {
merged[i] = first[i];
merged[i + 3] = second[i];
}
for (int num : merged) {
cout << num << " ";
}
With vectors, you do not need to know the size in advance. Use insert() to add all elements of one vector to the end of another:
Example
vector<int> first = {1, 2, 3};
vector<int> second = {4, 5, 6};
vector<int> merged = first;
merged.insert(merged.end(), second.begin(), second.end());
for (int num : merged) {
cout << num << " ";
}
Explanation:
In the first example, the elements of second are placed after the elements of first, starting at position 3.
In the second example, merged starts as a copy of first, and insert() adds the elements of second at the end.