TITLE: remove and erase for std::vector (Newsgroups: comp.lang.c++, 19 Jun 99) GIBSON: Adam Gibson > I've discovered I can get the thing to work like this: > vector v; > vector::iterator Iter; > Iter = remove(v.begin(),v.end(),i) // where i is the value to be removed > but I'm confused about the difference between remove and erase.. > Does remove just move the elements to be removed to the end, and then > reassign the return value of end()? > Does erase actually deallocate memory? KOENIG: Andrew Koenig You're almost right. Remove moves the elements to the beginning that are not to be removed, overwriting the removed ones in the process. It leaves some number of elements unchanged at the end, returning an iterator that refers to the first such element. Erase changes the size of the vector. The way to remember which is which is that algorithms that change the size of a container must know about the container in order to change its size, so foo(v.begin(), v.end(), args); cannot change the size of v, regardless of what foo represents. If it were to change the size of v, it would have to be v.foo(args); You still might not remember which is erase and which is remove, but as long as you remember whether you wanted a member function or not, the compiler will stop you: erase(v.begin(), v.end(), i); // error: erase undefined -------------------------------------------------------------------- (Newsgroups: comp.lang.c++, 21 Jun 99) NARAN: Siemel Naran wrote in message ... > >>The functions std::remove(...) and std::remove_if(...) don't actually > >remove elements! Instead, they basically return two ranges -- the > >first range has the elements that weren't removed and the second range > >has any elements. Eg, if your container was > > 1 2 3 2 1 > >and you removed the element '2', then your new container may be > > 1 3 1 2 1 > > ^ > >and std::remove(,..) returns an iterator to the position marked with > >the '^'. This position signifies the end of the new container. GIBSON: Adam Gibson wrote: > Siemel, > can I just check: > was this an error? > should the second list of numbers read: > 1 3 1 2 2 > ? > Or have I still not understood? KOENIG: Andrew Koenig You have not understood. Counting indices from zero, removing '2' from 1 2 3 2 1 does the following: 1 2 3 2 1 Element 0 is 1, so it won't be removed. Copy element 0 to element 0. 1 2 3 2 1 Element 1 is 2, so it will be removed. 1 2 3 2 1 Element 2 is 3, so it won't be removed. Copy element 2 into element 1 (the first free position). 1 3 3 2 1 Element 3 is 2, so it will be removed. 1 3 3 2 1 Element 4 is 1, so it won't be removed. Copy element 4 into element 2 (the first free position). 1 3 1 2 1 is the final result. The value returned will be an iterator referring to element number 3 (the first free position).