On 2005-02-22 15:12:12 -0500,
is******@gmail.com said:
Is there a fast way to crop a vector? I have a vector of size n, and
want to reduce it to some subregion (x,y ). Seems like you shouldn't
have to recopy all of those elements into a new vector, since they are
already contiguous in memory.
You will have to do some copying, as STL containers "own" the contained
objects. There is no way to transfer those objects to a new vector, or
make them outlive the container. It would be possible to write a
container that could do this (i.e. have it store five pointers:
"storage begin", "begin", "end" and "storage end"), but that could be
pretty wasteful in the general case.
There are several ways to accomplish what you want, but they all
involve copying in the general case:
Assuming:
v is a vector of <foo>
x and y are iterators pointing into v
1)
std::copy(x, y, v.begin());
v.resize(y-x);
2)
v.resize(y - v.begin());
v.erase(v.begin(), x);
3)
std::swap(v, std::vector<foo>(x,y));
.... among others. The only case that I can think of off the top of my
head where no copying is needed is if (x == v.begin()):
v.resize(y - x);
--
Clark S. Cox, III
cl*******@gmail.com