Search code examples
c++templatesstlconstantsdeclaration

Create const std::vector as the concatenation of two const std::vector


I would like to create a const std::vector to contain all the elements of two other const std::vector of the same type. Since the vector is const I can not concatenate it step by step with the two const std::vector using the method mentioned in Concatenating two std::vectors.

#include <iostream>
#include <vector>

int main()
{
    const std::vector<int> int_a{0,1};
    const std::vector<int> int_b{2,3};
    const std::vector<int> all_ints;
    
    for (int i: all_ints)
        std::cout << i << ' ';
    return 0;
}

For the example above I would like to define all_ints in a way that the output is 0 1 2 3.

How could that be done?


Solution

  • Make a function that takes the other two vectors, creates a third one, inserts values from the first two, returns the result by value. Then assign this to your const vector:

    const std::vector<int> int_a{0,1};
    const std::vector<int> int_b{2,3};
    const std::vector<int> all_ints = concat(int_a, int_b);