如何将2D数组插入3D数组C ++

问题描述 投票:0回答:1

我有一个这样的数组b

int b[4][4] = { {0,1,1,0} , {1,1,0,0} , {0,0,0,0} , {1,1,1,1} }

并且我想将其插入3D数组,因为不幸的是我无法拥有2D数组的向量。我希望能够向此3D阵列添加更多2D阵列。例如,如果“ a”是我的3​​D数组,我希望b成为它的一部分,以及另一个名为c的2D数组。有任何可行的方法吗?

c++
1个回答
0
投票

A std::vector无法有效使用数组,因为无法轻松分配,复制或移动数组。 Use a std::array instead

示例:

std::array

输出是

#include <vector>
#include <array>
#include <iostream>
int main()
{
    std::vector<std::array<std::array<int,4>,4>> vec;
    // make b. Note the extra set of braces surrounding the initializer list 
    std::array<std::array<int,4>,4> b = {{ {0,1,1,0} , {1,1,0,0} , {0,0,0,0} , {1,1,1,1} }};

    // add b to vector
    vec.push_back(b); 
    // add a temporary array. Note you can't emplace_back an brace-enclosed list. Bummer.
    vec.push_back(std::array<std::array<int,4>,4>{{ {1,0,0,1} , {0,0,1,1} , {1,1,1,1} , {0,0,0,0} }});

    // print everything out for proof
    for (const auto & outer: vec)
    {
        std::cout << "vector entry:\n";
        for (const auto & inner: outer)
        {
            for (const auto & val: inner)
            {
                std::cout << val << ' ';
            }
            std::cout << '\n';
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.