c++ - 一维 vector 到多维数组/vector

标签 c++ arrays vector multidimensional-array

我有一个刚从文件中读入的 float 的一维 vector 。

std::vector<float> result(s.size() / sizeof(float));

我想像这样使用这些数据

myTable[rl][gl][bl][0];

那么有什么简单的方法可以将我的一维 vector 转换为简单的多维 vector 或多维数组吗?

float myTable[100][10][20][30];
vector<vector<vector<vector<int> >>> myTable;

我仍然可以轻松地使用在整个代码中设置的索引。 并且不必必须将其转换为一维访问,例如:myTable[indexmathhere]

最佳答案

我实际上不会重写数据,除非您有缓存要求(尽管我们对您的数据布局一无所知)。

将 vector 存储在一个类中,并编写一个访问函数,该函数接受四个索引参数并执行必要的算法以将它们展平为单个 vector 索引。

class MyMatrix
{
   std::vector<float> result;

public:
   float at(int r, int g, int b, int a) const
   {
      return result[r+W*g+W*H*b+W*H*D*a];  // or whatevs
   }
};

您甚至可以编写一些 operator() 重载,但您需要三种代理类型才能从中获得四个维度的索引。

关于c++ - 一维 vector 到多维数组/vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998724/

相关文章:

c++ - 无法将 '(<expression error>)' 从 '<brace-enclosed initializer list>' 转换为 std::unique_ptr<int []>

c++ - boost 分配 : using objects with map_list_of?

C++ "Hello World.exe"崩溃 - 在命令提示符中使用时为 "Hello World.exe has stopped working."

c# - 数组实例化错误

c++ - std::vector<struct> 到 const std::vector<const struct>*

C++ std::vector 迭代器行为奇怪,不允许递增

c++ - c++ 阶乘程序中的递归

php - 检查数组是否递归

python - 一定范围内的随机数组

c++ - 二维数组错误: Vector index beyond memory allocation