1

I have a 1D dimensional vector of floats I just read in from a file.

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

I want to use this data like this

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

So is there any easy way to convert my 1D vector to a multidimensional vector or multidimensional array that is simple?

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

Where I can still easily use the indexing that is setup all over the code. and not have to convert it to a 1D access like : myTable[indexmathhere]

John Du
  • 227
  • 2
  • 9

2 Answers2

1

I wouldn't actually rewrite the data, unless you have cache requirements (though we don't know anything about the layout of your data).

Store the vector inside a class, and write an accessor function that takes four index arguments and performs the necessary arithmetic to flatten them into the single vector index.

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
   }
};

You could even write some operator() overloads, but you'd need three proxy types to get four dimensions of indexing out of that.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
0

If you have fixed size array you probably should use std::array. Something like it is in this question: Multidimensional std::array Unfortunately, there is no oneliner to put your data into this array, you need to do it manually.

Community
  • 1
  • 1
  • You didn't answer the question. – Lightness Races in Orbit Jan 08 '14 at 15:39
  • I did. Question was: "So is there any easy way to convert my 1D vector to a multidimensional vector or multidimensional array that is simple?" No. Should I write code for him? I'm not interested in that, thank you. Code is trivial btw. – son of the northern darkness Jan 08 '14 at 15:51
  • I never asked you to write code for him. I am saying, answer the question instead of "change to a different container" which is completely besides the point. – Lightness Races in Orbit Jan 08 '14 at 15:54
  • Ok. Point accepted. std::array allows to avoid temptation to push_back for example, which would cause memory reallocation. For this size of array on desktop system std::array would be first choice for me. Your solution is fine be me but it is not that TS asked either. – son of the northern darkness Jan 08 '14 at 16:03