简体   繁体   中英

How can I manipulate size of(vector,deque…) inside generic function using iterators?

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM