如何在C++中定义每个维度具有不同类型的 3D 数组

How to define a 3d array with each dimension a different type in C++?

本文关键字:同类型 数组 3D C++ 定义      更新时间:2023-10-16

我想定义一个这样的 3D 数组:

Type ary[3/*enumeration type*/][6/*int*/][7/*const wchar**/];

在C++可能吗?我正在使用Visual Studio 2010,不允许使用Boost库。如果可能,请告诉我如何初始化每个维度?

以下内容可能会对您有所帮助:

template <typename T, std::size_t N, typename IndexType>
class typed_array
{
public:
    typedef typename std::array<T, N>::const_iterator const_iterator;
    typedef typename std::array<T, N>::iterator iterator;
public:
    const T& operator [] (IndexType index) const { return array[int(index)]; }
    T& operator [] (IndexType index) { return array[int(index)]; }
    // discard other index type
    template <typename U> const T& operator [] (U&&) const = delete;
    template <typename U> T& operator [] (U&&) = delete;
    const_iterator begin() const { return array.begin(); }
    const_iterator end() const { return array.end(); }
    iterator begin() { return array.begin(); }
    iterator end() { return array.end(); }
private:
    std::array<T, N> array;
};
enum class E { A, B, C };
int main(int argc, char *argv[])
{
    typed_array<int, 3, E> a;
    typed_array<typed_array<int, 4, char>, 3, E> b;
    //a[2] = 42; // doesn't compile as expected. `2` is not a `E`
    b[E::A][''] = 42;
    //b[E::A][2] = 42; // doesn't compile as expected. `2` is not a `char`
    return 0;
}

这是不可能的,因为它是同一类型的数组元素。

struct s_i {
    int i;
    const wchar *wc[7];
};
struct s_e {
    enum Ex e;
    struct s_i i[6];
} ary[3];

不,这是不可能的。

你可以做的是创建一个表现为枚举的类,并有一个下标运算符,该运算符返回另一个特殊类(通常表现为int),该类具有下标运算符,该运算符又返回wchar_t数组。