1

I have some C++ code where I am declaring 2D arrays using "vector" with the following method:

    std::vector<std::vector<double>> Array2D(X, std::vector<double>Y);

where X and Y are the dimensions of the array.

This works beautifully for what I need to achieve. However I would like to look at using the same method for 3D, XYZ arrays. I assume I start with:

    std::vector<std::vector<std::vector<double>>>

but how do I declare the dimensions, ie Array3D(X, ?????)

4
  • Would you mind posting a minimal reproducible example please. Commented Oct 9, 2015 at 0:40
  • 3
    DON'T use such nested vectors to create 3D matrices. They are slow, since the memory is not guaranteed to be contiguous anymore and you'll get cache misses. Better use a flat vector and map from 3D to 1D and viceversa. Commented Oct 9, 2015 at 0:49
  • @vsoftco how to use a flat vector and map from 3D to 1D? Commented Oct 21, 2021 at 10:44
  • 2
    @Ahmetİnal (X,Y,Z) -> (X + Y * DX + Z * DY * DX), where DX and DY are the dimensions on X and Y, respectively Commented Oct 22, 2021 at 11:21

2 Answers 2

7

There is fill vector constructor, which constructs a container with n elements, and each element is a copy of value provided.

std::vector<std::vector<std::vector<double>>> Array3D(X, std::vector<std::vector<double>>(Y, std::vector<double>(Z)));

will create X by Y by Z vector. You probably would like to use typedef for this type.

Sign up to request clarification or add additional context in comments.

1 Comment

Legend. Spot On. That is exactly what I was after. Cheers
3

You can declare like

 std::vector<std::vector<std::vector<double> > > Array3D(X, std::vector<std::vector<double> >(Y, std::vector<double>(Z)));

Where X, Y, Z are the dimension of 3D vector.

NB

It's better not to use 3D vector as mentioned by vsoftco

DON'T use such nested vectors to create 3D matrices. They are slow, since the memory is not guaranteed to be contiguous anymore and you'll get cache misses. Better use a flat vector and map from 3D to 1D and viceversa.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.