Search code examples
c++arraysinitializationconcatenation

C++ initialize array with another array and new values


I'm coming to C++ from python and would like to do the equivalent of this with arrays if possible:

both = [...]
a = [a1, a2] + both
[a1, a2, ...]
b = [b1, b2] + both
[b1, b2, ...]

Solution

  • To do such a thing with arrays you might consider the following code

        #include <iostream>
        
        int main()
        {
            int both[] ={1, 2, 3};
            std::cout << sizeof(both)/sizeof(*both);
            int a[sizeof(both)/sizeof(*both) + 2] = {4, 4};
            int b[sizeof(both)/sizeof(*both) + 2] = {5, 5};
            for (int i = 0; i < sizeof(both)/sizeof(*both); ++i)
            {
                a[2+i] = both[i];
                b[2+i] = both[i];
            }
        
            return 0;
        }
    

    But since you are using c++, not c, you might really consider using one of the containers offered by c++ standard library