merging different vectors into one vector

  array-merge, c++, vector

I have a collection of vectors and want to merge them into one big vector. I’ve written a function
that takes in a list of integers, which all represent a different vector(e.g. v1 and v2), and returns a vector containing all the elements of the desired vectors.

std::vector<int> mergeVectors(std::vector<unsigned int> indices) {
    
    std::vector<int> v1 = {0, 1, 2};
    std::vector<int> v2 = {3, 4, 5};


    std::vector<int> returnVector;

    for (unsigned int index : indices) {
        switch (index) {
            case 0:
                returnVector.insert(returnVector.end(), v1.begin(),
                                     v1.end());
                break;
            case 1:
                returnVector.insert(returnVector.end(), v2.begin(),
                                     v2.end());
                break;
            default:
                break;
        }
    }
    return returnVector;
}

I’d like it to work as follows:

mergeVectors({0}); should just return {0, 1, 2}.

mergeVectors({0,1}) should return {0, 1, 2, 3, 4, 5}.

However the method always just returns {}.

Source: Windows Questions C++

LEAVE A COMMENT