Reputation: 710
I was implementing an algorithm that needs me to remove and add the same elements from a vector each iteration of a loop.
Example:
iteration 1 : |1 2 3 4| (size 4)
iteration 2 : |1 3| 2 4 (size 2 with the elements '2' and '4' still there in memory but not accounted for in the size of the vector)
iteration 3 : |1 2 3| 4 (size 3 with the element '4' still there)
Basically, I want to be able to change the value returned by the size() function without affecting the vector for performance reasons.
I know I could use another variable outside of my vector to keep track of its size, but I wanted to know if it could be possible directly internally in the std::vector container.
Thanks for any help.
Upvotes: 2
Views: 4893
Reputation: 3992
I don't know, maybe use has-a
instead of is-a
?
template <typename T> class subvector {
protected:
std::vector<T> owner_;
std::size_t begin_;
std::size_t end_;
public:
subvector(std::vector<T>& owner, size_t from, size_t to) :
owner_(owner), begin_(from), end_(to)
{
// do some range checks
}
size_t size() const {
// range check before return
// either throw (fast-fail) *or*
// adjust the out-of-range ends (lenient but maybe unsafe)
return end_-begin_+1;
}
// implement as many of the std::vector methods/operators
// you are likely to need in your code by delegation
// to the owner_.
// Stay minimal, whenever you use something you don't have,
// the compiler will tell you.
};
Upvotes: 3
Reputation: 36597
You can't do that.
The only way to reduce the value reported by size()
is to resize. When resizing reduces the size, the elements outside the new size no longer exist as far as the program is concerned. Any means of accessing them (or reaccessing them, in your case) yields undefined behaviour.
If you want to track the number of elements of an array in use (say, that you are using two elements of a vector with five elements) then create an extra variable to keep track of that. To state the (hopefully) obvious, that variable will need to be kept consistent with the size of the vector (e.g. to avoid tracking that ten elements are being used in a vector with five elements).
If you want to keep the variable with the vector, make both members of a struct
/class
type. That class can provide member functions or operations that manage both the vector and the number of elements "in use", to ensure consistency.
Upvotes: 5
Reputation: 473272
What you want is logically inconsistent with how vector
works. size
returns the number of objects of type T
in the vector
. By reducing that size, any objects chopped off the end are destroyed. When you increase the size, you are adding new objects.
It would be better to build a type around vector
that has the behavior you want.
Upvotes: 8