【问题标题】:How to define a 3d array with each dimension a different type in C++?如何在 C++ 中定义每个维度不同类型的 3d 数组?
【发布时间】:2014-01-13 08:00:38
【问题描述】:

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

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

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

【问题讨论】:

  • 所以你的每个维度都有不同的类型?
  • 是的,这在现实生活中很常见。
  • 在某种程度上是可能的
  • @BLUEPIXY 我认为他希望每个枚举类型都有与之关联的 int 数组,并且每个 int 值都有 wchar 数组。这就是他问 3D 数组的原因。
  • 你可以试试 std::map stackoverflow.com/a/3927754/2648826

标签: c++ visual-studio-2010 data-structures stl


【解决方案1】:

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

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]['\0'] = 42;
    //b[E::A][2] = 42; // doesn't compile as expected. `2` is not a `char`

    return 0;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 可以用table-driven的方式初始化吗?
    • @Triumphant 我想我不知道 Table-Driven 的含义,但是能够以与数组相同的方式。
    【解决方案3】:

    不,这是不可能的。

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

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2012-12-23
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多