我不知道您是要像交错那样合并它们还是只是连接两个不同的数组。如果它正在大步前进:
#include <iostream>
void mergeTwoArraysIntoOne(const int* lhs, const int* rhs, int* dst, size_t numElements) {
const int* const endLhs = lhs + numElements;
const int* const endRhs = rhs + numElements;
for ( ; lhs < endLhs ; ) {
while (rhs < endRhs && *rhs < *lhs)
*(dst++) = *(rhs++);
*(dst++) = *(lhs++);
}
while (rhs < endRhs)
*(dst++) = *(rhs++);
}
void dumpArray(int* array, size_t elements) {
for (size_t i = 0; i < elements; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main() {
int array1[] = { 1, 2, 3 };
int array2[] = { 10, 20, 30 };
int array3[] = { 1, 11, 31 };
int result[6];
mergeTwoArraysIntoOne(array1, array2, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array2, array1, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array1, array3, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array3, array1, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array2, array3, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array3, array2, result, 3);
dumpArray(result, 6);
return 0;
}
现场演示:http: //ideone.com/7ODqWD
如果只是连接它们:
std::copy(&lhs[0], &lhs[numElements], &dst[0]);
std::copy(&rhs[0], &rhs[numElements], &dst[numElements]);