c++ - 按行、列和深度顺序打印多维 vector

标签 c++ multidimensional-array vector printing

我正在尝试按行 x 列 x 深度的顺序打印 3D vector 数组,但结果有所不同。例如我想打印一个 3x2x5 vector 数组,我的代码输出是:

1 1 1 1 1
1 1 1 1 1

1 1 1 1 1
1 1 1 1 1

1 1 1 1 1
1 1 1 1 1

输出类似于:2(行)x 5(列)x 3,我觉得不对。

这是我的代码...

#include <iostream>
#include <string>
#include <vector>

const int N = 3;
const int M = 2;
const int Q = 5;

typedef std::vector<double> dim1;
typedef std::vector<dim1> array2D;
typedef std::vector<array2D> array3D;

array2D A(N, dim1(M));
array2D B(N, dim1(M));
array3D C(N, array2D(M, dim1(Q)));

int main() {

    for (int ix = 0; ix < N; ++ix) {
        for (int iy = 0; iy < M; ++iy) {
            for (int iq = 0; iq < Q; ++iq) {
                C[ix][iy][iq] = 1.0;
            }
        }
    }
    for (int ix = 0; ix < N; ++ix) {
        for (int iy = 0; iy < M; ++iy) {
            for (int iq = 0; iq < Q; ++iq) {
                std::cout << C[ix][iy][iq];
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }

return 0;

}

最佳答案

你几乎可以正常工作了。我看到您的代码中唯一缺少的是连续数字之间的空格。

std::cout << C[ix][iy][iq] << " ";
                           ^^^^^^

即使在行的最后一个数字之后也会添加一个空格。如果这是 Not Acceptable ,您将需要一些额外的逻辑:

for (int iq = 0; iq < Q; ++iq) {
    std::cout << C[ix][iy][iq];
    if ( iq < Q-1 ) {
       std::cout << " ";
    }
}

关于c++ - 按行、列和深度顺序打印多维 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602679/

相关文章:

java - 为什么我的二维数组克隆不止一次?

c++ - 并行分配给 std::vector<std::vector<double>>

c++ - 从 std `vector` 库创建的 `<vector>` 和从 : `STL vector` 创建的 `<STL_vector.h>` 之间的区别

c++ - std::vector<std::vector<int>> push_back 给出堆缓冲区溢出

c++ - map 内容未以特定方式打印

c++ - 使用空终止字符数组调试断言失败错误

c++ - 在 C++ 中使用静态类成员

c++ - 我什么时候应该防止隐式破坏?它是如何工作的?

c++ - 抽象类的二维数组?

c - 使用二维数组存储多个字符串