0

I have a 4D vector of following type:

vector< vector< vector< vector< unsigned > > > > vec I don't know the size of the 4th dimension at the beginning, so I am trying to resize the first 3 dimension in the following way:

vec.resize(x.size(), vector< vector< vector< unsigned > > >
(y.size(), vector< vector< unsigned > >(2)));

where x and y are of type vector<unsigned>

After I resized the first 3 dimensions in the above way mentioned I can't access any element from dimension 3(i.e vec[i][j][1]).

Can anyone please suggest what am I missing here?

  • 3
    I think using `using` or `typedef` would simplify this a lot. – PaulMcKenzie Apr 05 '17 at 22:44
  • Why resize them? Why not create them the correct size, except for the 4th, and then resize that> –  Apr 05 '17 at 22:49
  • because this vector has to be global and I think I can only declare the size of a vector inside a function @NeilButterworth – Fabia Bushra Tamanna Apr 05 '17 at 22:53
  • "I think I can only declare the size of a vector inside a function" Nope. And I'm pretty sure it doesn't have to be global. –  Apr 05 '17 at 22:55
  • @FabiaBushraTamanna -- *I can't access any element from dimension 3* -- What error do you get? A compiler error? Runtime error? – PaulMcKenzie Apr 05 '17 at 22:56
  • Can I talk you into a nice, 1 dimensional vector with in a wrapper class that makes it look like a 4D array? Hell of a lot easier to use. Probably faster, too. – user4581301 Apr 05 '17 at 22:57
  • After applying somewhat sane `typedef`'s, [cannot duplicate](http://ideone.com/6V8a5n). The code above accesses the 3 dimensions with no issue. So is it a runtime error you're getting, and not something to do with syntax? – PaulMcKenzie Apr 05 '17 at 23:00
  • no I tried to insert element using vec[i][j][1].insert(). But no suggestion comes up, that means I couldn't allocate any space for that vector position @PaulMcKenzie – Fabia Bushra Tamanna Apr 05 '17 at 23:04
  • If you're going by IDE suggestions, change your code to `auto& v1 = vec[i][j][1];`. Then call `v1.insert(whatever);` – PaulMcKenzie Apr 05 '17 at 23:06
  • 1
    This is a cache locality nightmare. Until you know the 4th dimension, your structure cannot store any data, apart from a whole bunch of structure and pointers. You're better off writing a simple class to keep your actual data in a single allocated block. You can then use `std::valarray` or similar to interact with the data via whatever indexing methods you choose to provide. – paddy Apr 05 '17 at 23:39
  • https://stackoverflow.com/questions/35008089/elegantly-define-multi-dimensional-array-in-modern-c – sailfish009 Apr 06 '17 at 00:47

0 Answers0