I have a 3D vector and I want to be able to chose which dimension to plot as a function of another dimension.
So far, I am doing this manually: I create a second 3D vector and re-organize the data accordingly. This solution is not very practical since I need to switch the indexes (inside the nested loop) every time I want to switch the dimensions...
Is there a better/cleaner solution ?
Thanks.
C++ does not provide multidimensional containers for the same reason that containers like std::vector
do not provide a standard operator+
etc.: there is no standard that fits everyone's needs (in the case of a +
operator, this could be concatenation, element-wise addition, increasing the dimensionality, who knows). If instead of a vector you take a class
<template typename T>
class volume {
private:
std::vector<T> data; // e.g. 3x2 array { 0, 1, 2, 3, 4, 5 }
std::vector<size_t> sizes; // e.g. 3x2 array { 3, 2 }
std::vector<size_t> strides; // e.g. 3x2 array { 1, 3 }
};
then you have all the flexibility you want - no need to stop at 3D!
As an example the data
vector of a 3x2 array could be the first 6 natural numbers, the sizes
vector would be { 3, 2 }
and the strides array { 1, 3 }
: in a row (of which there are 2) the elements are next to each other, to increase the row you need to move 3 positions forward.
In the general n-dimensional case you can make an at()
operator that takes a vector (or an initializer_list
) as a position argument, and the offset corresponding to that position is its inner product with strides
.
If you don't feel like programming this from scratch then libraries like Blitz++ already provide this functionality.