3

i have a quick question about having a reference to a subset of a collection. Consider i have a vector of objects. Now I want to create another vector which is a subset of this vector, and I dont want to create a copy of the subset of objects.

One of the ways I was thinking about is creating a vector<auto_ptr<MyClass> >. Is this a good approach? Please suggest if you think any other containers or idioms or patterns would help in this case. Thank you

icecrime
  • 74,451
  • 13
  • 99
  • 111
Chenna V
  • 10,185
  • 11
  • 77
  • 104

4 Answers4

7

No ! See : Why it is wrong to use std::auto_ptr<> with STL containers ?

Now, as an alternative, you could store raw pointers or boost::shared_ptr depending on your needs.

Community
  • 1
  • 1
icecrime
  • 74,451
  • 13
  • 99
  • 111
  • If you delete the vector that implements the subset, won't `shared_ptr` delete all the objects in the subset? (i assume the "larger" collection is of type `vector`) – anatolyg Dec 21 '10 at 17:44
  • so do you mean using an array of shared_ptr's ?? – Chenna V Dec 21 '10 at 19:08
  • @user519770: a `std::vector >` is a solution (as opposed to `std::auto_ptr`, `shared_ptr` copies are equivalent) – icecrime Dec 21 '10 at 19:10
2

Another, possibly more STL way would be to just have the one vector but keep track of sub ranges using pairs of iterators (note all the algorithms use iterators for exactly this reason)

jk.
  • 13,817
  • 5
  • 37
  • 50
0

If the subsection is contiguous you can reference the subsection using an iterator and a count indicating how many items you are referencing.

The sane way to do this would be to create some sort of templated class which you could construct with a container reference and two indices, and let the class do all the bounds and error checking, though I'm unsure how you'd be able to tell if the underlying container still existed at some later time...

Troyseph
  • 4,960
  • 3
  • 38
  • 61
0

You can use a vector of indices: vector<int> (or vector<size_t> if you want to be pedantic). This is better than storing pointers (pointers in a general meaning: raw C/C++ pointers, shared_ptr, iterator, etc) if the containing vector is not constant.

Consider the following scenario: the "big" vector contains an apple, an orange and a lemon, while the "small" vector contains a pointer to the apple. If you add a bunch of other fruits to the big vector, the STL is going to reallocate storage for the vector, so the pointer to the apple will be invalid (point to deallocated memory).

If the above scenario is possible, use a vector of indices. If it is not possible, use the other techniques (e.g. a vector of raw pointers, or a vector of copies of the objects).

anatolyg
  • 26,506
  • 9
  • 60
  • 134