How can I initialize 2d array with a list of 1d arrays?

前端 未结 4 1806
孤街浪徒
孤街浪徒 2021-01-18 05:21

How can I initialize 2d array with a list of 1d arrays?

void main()
{
    int a[] = { 1,2,3 };
    int b[] = { 4,5,6 };
    int array[][3] = { a,b };
}
         


        
4条回答
  •  野的像风
    2021-01-18 05:40

    raw arrays in C++ are kind of second class citizens. They can't be assigned and they can't be copied, which means you can't use them to initialize other arrays, and their name decays into a pointer in most circumstances.

    Lucky C++11 offers a solution. std::array acts like a raw array, but it doesn't have the drawbacks. You can use those instead to build a 2d array like

    std::array foo = {1,2,3};
    std::array bar = {3,4,5};
    std::array, 2> baz = {foo, bar};
    

    and if you have C++17 support you can leverage class template argument deduction to get rid of having to specify the template parameters and the code simplifies to

    std::array foo = {1,2,3};
    std::array bar = {3,4,5};
    std::array baz = {foo, bar};
    

    which you can see working in this live example

提交回复
热议问题