1

In the structure of my application it makes sense for one object to have a vector that is a subset of another vector. And I really mean that the storage of the smaller is contained in the storage of the larger.

Is this possible in C++? I promise that neither vector will ever be resized, and I can probably make it so that the subvector gets destructed before the containing one.

At first I thought that creating a subvector from iterators into the big vector would do the trick, but that makes a copy. I really want a redirect of the bare pointer.

Victor Eijkhout
  • 5,088
  • 2
  • 22
  • 23
  • 1
    Is your subset contiguous, meaning `v[i]` to `v[j]` and all the elements in between; or evenly strided, for example every third element of the original vector; or something more general? – aschepler Jul 02 '19 at 23:41
  • Contiguous. Really, this is the most innocuous and safe case. I'll investigate `gsl::span` which is new to me. – Victor Eijkhout Jul 03 '19 at 16:38

1 Answers1

5

In a word, no. std::vector just doesn't do that. But there are two similar things you can do:

  1. A vector of pointers (perhaps std::shared_ptr), such that one vector points at elements from the other. Of course, now you have a vector of pointers to the object, not the object, which may be a problem. One possible idea is std::reference_wrapper, but it's not great.

  2. There's also std::span, which is made for this use case.

Steven Sudit
  • 19,391
  • 1
  • 51
  • 53