如何为 3D 矢量声明多个值

How do I declare multiple values for a 3D vector?

本文关键字:声明 3D      更新时间:2023-10-16

我有 typedef typedef std::vector<std::vector<std::vector<double>>> three_d_vector;来声明 3D 向量;但我想知道如何,如果可以的话,如何在批量列表中声明各个值,就像数组一样。

假设您正在研究 C++11,并且您所要求的是初始化向量的直接方法:

#include <vector>
using namespace std;
int main()
{
    typedef vector<vector<vector<double>>> three_d_vector;
    three_d_vector v =
    {
        {
            { 1, 2, 3 }, { 4, 5, 6 }
        },
        {
            { 0, 0, 1 }, { 1, 0, 0 }
        },
        {
            { 4, 0, 1 }, { 1, 0, 5 }
        },
    };
}

但是,请注意,以这种方式定义 3D 矢量将使您能够自由地为每个维度使用不同的矢量大小。换句话说,这将是合法的:

    three_d_vector v =
    {
        {
            { 1, 2, 3, 7 }, { 4, 5, 6 }
        },
        {
            { 0, 0, 1 }, { 1, 0, 0, 8, 9, 15 }
        },
        {
            { 4, 0, 1 }, { 1, 0 }
        },
    };

这是需要的,可接受的还是不可接受的取决于你的用例;无论如何,我想你可能想看看Boost.MultiArray

您需要

在 C++11 模式下编译(例如,使用 gcc 的命令行开关-std=c++11)并使用如下语法:

three_d_vector vec = { { {1., 2.}, {3.,  4., 17., 25.} },
                       { {5., 6., 12.}, {7.,  8.}, {0., 22.} },
                       { {9., 10.}, {11.}, {45.}, {33.}, {37., 11.} };

使用std::vector<std::vector<std::vector<double>>>不会非常连贯。请改用Boost.MultiArray