0

I have a job to make a generic function that recieves an iterator to first, and iterator as reference to last element(of vector,deque...) my job is to filter out some elements. Is it possible to delete elements and reseize the container ? Thank You!

ugursuz
  • 35
  • 6
  • 1
    Should be able to use the [erase-remove idiom](https://stackoverflow.com/questions/39019806/using-erase-remove-if-idiom) depending on which containers you intend to target – Cory Kramer Apr 17 '20 at 11:58
  • If you only are getting iterators, the problem is that the `erase` is a member function of the container, and is not generic. Looks like you're reinventing `std::remove` and `std::remove_if`. – PaulMcKenzie Apr 17 '20 at 12:00
  • 1
    No, it's not possible. Look at how [`std::remove`](https://en.cppreference.com/w/cpp/algorithm/remove) works. – molbdnilo Apr 17 '20 at 12:00
  • you cant resize a container that you don't own. you just have its boundaries (iterator to its first and last element) – Moe Apr 17 '20 at 12:03
  • 1
    @CoryKramer erase-remove idiom still requires access to container, iterators are not enough – Slava Apr 17 '20 at 12:19
  • Thank You everybody, you've been helpful! ;) – ugursuz Apr 18 '20 at 11:25

2 Answers2

2

No, it's not possible. erase() is a method of the container, and you can't reach the container from an iterator.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Or container may not have `erase()` method or alike at all. For example embedded array. – Slava Apr 17 '20 at 12:21
0

In general you cannot modify size of container which content passed to you by pair of iterators. If it would be possible it would be quite strange though. What if only part of container is passed to you as a range? What if 2 pointers to content of embedded array is passed to you? How are you going to resize an embedded array?

With your restriction (2 iterators passed as a range) only viable solution is to do, what std::remove() does - rearrange elements so you would have 2 ranges as a result, elements to keep and rest of them and return an iterator that shows where is the border ie where range of elements to be erased starts. This iterator also can be treated as a new end if you want to pass range of valid elements to further algorithms without even resizing the container.

Slava
  • 43,454
  • 1
  • 47
  • 90