我有一个关于引用集合子集的快速问题。
考虑我有一个对象向量。现在我想创建另一个向量,它是该向量的子集,并且我不想创建对象子集的副本。
我正在考虑的方法之一是创建一个 vector >
。这是一个好方法吗?
如果您认为任何其他容器、习语或模式在这种情况下会有所帮助,请提出建议。
谢谢
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
发布评论
评论(4)
不!请参阅:为什么使用std::auto_ptr是错误的<>使用 STL 容器?
现在,作为替代方案,您可以根据需要存储原始指针或
boost::shared_ptr
。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.另一种可能更 STL 的方法是只拥有一个向量,但使用成对的迭代器跟踪子范围(请注意,所有算法都使用迭代器正是出于这个原因)
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)
您可以使用索引向量:
vector
(如果您想学究气,则可以使用vector
)。这比存储指针(一般含义的指针:原始 C/C++ 指针、shared_ptr
、iterator
等)如果包含的向量不是常量< /强>。考虑以下场景:“大”向量包含一个苹果、一个橙子和一个柠檬,而“小”向量包含一个指向苹果的指针。如果将一堆其他水果添加到大向量中,STL 将为该向量重新分配存储空间,因此指向苹果的指针将无效(指向已释放的内存)。
如果上述情况可行,请使用索引向量。如果不可能,请使用其他技术(例如原始指针向量或对象副本向量)。
You can use a vector of indices:
vector<int>
(orvector<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).
如果该小节是连续的,您可以使用迭代器和指示您引用的项目数的计数来引用该小节。
执行此操作的明智方法是创建某种模板化类,您可以使用容器引用和两个索引来构造该类,并让该类执行所有边界和错误检查,尽管我不确定您如何能够判断底层容器在稍后的时间是否仍然存在......
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...