In my program I use boost::multi_array and sometimes it is important to convert a pointer to an element inside the container into its indices, for example, to check that the element is not on the boundary of the array by any dimension. Here is oversimplified code just to explain the intension:
boost::multi_array<int, 2> arr2d(boost::extents[10][10]);
const auto data = arr2d.data();
const auto end = data + arr2d.num_elements();
for ( auto it = data; it != end; ++it )
{
[[maybe_unused]] int v = *it;
// how to convert it into x and y indices in arr2d?
}
Is there any build-in valid means in boost::multi_array for pointer-to-indices conversion? Or the only possibility is manual division of the offset relative to data start on the dimensions?
This facility does not seem to be in the library. Which is a bit of a shame, but makes sense from the interface/use cases for the library.
I came up with this solution which takes into account all storage orderings/directions, and base indexes:
Because this is way too much logic not to test it I came up with a rigorous test:
This causes the mapped coordinates to be printed for every element in memory order:
And also checks all elements:
Then I ran it on a variety of test matrices:
This prints
Full Listing
Live On Compiler Explorer