1

Suppose we are given std::vector<T> V and an iterator p to a position within the vector.

Q1: What is a good way to return a new vector w for which the given iterator p is std::end(w)?

I could create a new vector w, move the elements from std::begin(v) to p and assign p = std::end(w).

Q2: Is there a way to do what I want but keeping p const ?

The origin of my question is the following: I have a vector for which I applied std::remove(std::begin(v),std::end(v), elem). This should put all the elements that are not equal to elem and return an iterator to the end of that range. I would like to clip the vector there.

myfirsttime1
  • 287
  • 2
  • 12

1 Answers1

7

You can do this:

std::vector<T> w = v;
v.erase(p, v.end());
w.swap(v);

Now p is an iterator into w, p == w.end(), and v is the original vector. Note that swapping two dynamic containers (with appropriate allocators) makes iterators of one container become iterators of the other container.

This doesn't quite work for returning values from functions, because there is no similar guarantee for move construction, nor is copy elision mandatory.


However, given that you say that p is the result of remove, maybe a simpler solution would be the typical remove-erase idiom:

v.erase(std::remove(std::begin(v),std::end(v), elem), std::end(v));
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084