0

I would like to have array-like objects that support multiple arrays pointing to the same memory region. Something that would look like this with good old raw pointers:

#include <iostream>

int main()
{
    double* array{new double[100]};
    double* subarray{array + 5};

    std::cout << array[5] << std::endl;
    subarray[0] = 33.0;
    std::cout << array[5] << std::endl;

    delete[] array;
    return 0;
}

Something that would look like

Foo array{100, 3.0};
Foo subarray{array.slice(40,50)};
assert(&array[43] == &subarray[3]);

As far as I see, things like std::vector and std::valarray would required copying the subsection into a new object, which is not what I want. I could not find anything else. I am happy to implement my own solution, but is there anything I could use?

Sergio Losilla
  • 730
  • 1
  • 5
  • 14

1 Answers1

0

The Modern C++ way to do this sort of thing is to use a pair of iterators. I believe Boost has a library to do basically what you describe, but all of the STL algorithms work on pairs of iterators to allow you to do what you describe. So if you want to talk of the range from element 10 to element 20 (half open, of course) of a std::deque, you use std::begin(d) + 10 to std::begin(d) + 20 as your range.

Ron
  • 14,674
  • 4
  • 34
  • 47
Ben
  • 9,184
  • 1
  • 43
  • 56