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.

#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.

Is that possible and how could it be done?

>Solution :

I actually don’t know what’s the essence of creation of const vectors like this. But a simple hack is to create a temporary non-const vector and fill it with the first two vectors, then create the final const vector. eg:

const std::vector<int> int_a{0,1};
const std::vector<int> int_b{2,3};
std::vector<int> middle(a);
middle.insert(middle.begin(),b.begin(),b.end());
const std::vector<int> all_ints(middle);

As suggested in comments, the last line could be written as:

const std::vector<int> all_ints = std::move(middle);

Leave a Reply