【问题标题】:Cant make a vector of fixed size arrays?无法制作固定大小数组的向量?
【发布时间】:2013-06-06 19:32:04
【问题描述】:

我有这个奇怪的问题

    vector<unsigned int[3]> tris;
    for (unsigned int i = 0; i < idx.size() - 2; i++) {
        unsigned int push[] = {idx[i], idx[i+1], idx[i+2]};
        tris.push_back(push); //<- this is where it goes belly up
    }

该代码片段应该将三角形带状索引列表分解为三角形索引,但不会在 vs10 下编译。想法?

【问题讨论】:

    标签: c++


    【解决方案1】:

    不,除非您将数组包装成 struct 或使用 std::array 之类的东西。

    裸 C 风格的数组类型不可复制或分配,这使得它不能用作标准容器元素。

    附:应该注意的是,C++11 切换到了更精细的(按方法)方法来指定容器元素类型的要求,而不是 C++03 使用的更广泛的方法。上述不合格声明基于 C++03。我还没准备好说它对于 C++11 也是如此无条件地正确……但如果你坚持在代码中使用 push_back,即使在 C++11 中它也肯定是正确的。

    附言在 C++11 中,人们可能会使用 std::list 的裸 C 样式数组并使用 emplace 构造新元素。但不是std::vector

    【讨论】:

    • 这是更好的答案,因为它简洁地指出了为什么示例无效,而不仅仅是要做什么。
    【解决方案2】:

    请改用std::vector&lt;std::array&lt;unsigned, 3&gt;&gt;

    【讨论】:

    • 这个答案看起来有效,但它没有。我的意思是,它之所以有效,是因为它将所有内容都布置在一个平坦的连续字节序列中。但是你不能对它做push_back(arr) 并希望它会附加新的arr。但是你可以使用std::memcpy
    【解决方案3】:

    如果您使用的是 C++11,则可以使用元组。

    std::vector < std::tuple< unsigned int, unsigned int, unsigned int > > tris;
    

    https://stackoverflow.com/a/15734156/846686

    一个不太“优雅”的解决方案可以是一对一对

        std::vector < std::pair< unsigned int, std::pair<unsigned int, unsigned int> > tris;
    

    但它可能会导致代码阅读起来非常混乱......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2012-03-17
      • 2022-11-02
      相关资源
      最近更新 更多