How do I merge two containers efficiently with std::vector for large datasets?

Merging two containers in C++ efficiently, especially when dealing with large datasets, is a common requirement. Using `std::vector` to perform this task can lead to significant performance improvements when handled correctly. Below is a simple and efficient way to merge two `std::vector` containers.


#include <iostream>
#include <vector>
#include <algorithm>

void mergeVectors(const std::vector<int>& vec1, const std::vector<int>& vec2, std::vector<int>& result) {
    // Reserve space for the merged vector to avoid reallocations
    result.reserve(vec1.size() + vec2.size());

    // Merge both vectors
    result.insert(result.end(), vec1.begin(), vec1.end());
    result.insert(result.end(), vec2.begin(), vec2.end());

    // Sort the merged vector if needed
    std::sort(result.begin(), result.end());
}

int main() {
    std::vector<int> vector1 = {1, 3, 5, 7, 9};
    std::vector<int> vector2 = {2, 4, 6, 8, 10};
    std::vector<int> mergedVector;

    mergeVectors(vector1, vector2, mergedVector);

    for (const int& elem : mergedVector) {
        std::cout << elem << " ";
    }

    return 0;
}
    

C++ merge vectors std::vector efficient merging large datasets performance optimization