C++ 用另一个数组和新值初始化数组

C++ initialize array with another array and new values

我是从 python 转到 C++ 的,如果可能的话,我想用数组做同样的事情:

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

您可以使用 std::vector

std::vector<int> both = {...};

std::vector<int> a = {a1, a2};
a.insert(a.end(), both.begin(), both.end());

std::vector<int> b = {b1, b2};
b.insert(b.end(), both.begin(), both.end());

要对数组做这样的事情,您可以考虑以下代码

    #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;
    }

但是由于您使用的是 c++,而不是 c,您可能真的会考虑使用 c++ 标准库提供的容器之一