Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading