Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is the code:
C++
for (int i = start; i < end; i++) {
  int pos = i;
  std::vector<char>::iterator it = (newArr.begin() + pos);
  newArr.erase(it);

newArr is a char vector. This crashes the program. I also tried doing just newArr.erase(newArr.begin()+pos) but same result.

What I have tried:

I tried changing the iterator code to just newArr.erase(newArr.begin()+pos) and it did not work any better.
Posted
Updated 3-Dec-21 10:38am

You're creating iterators that point past the array after you've erased the first elements! Trying to erase invalid iterators then crashes the program.

You need to make sure that pos actually is a valid index at the time when you call erase!

Example:
if newArr has 2 elements, and your loop iterates from 0 to 1, then the first iteration will erase the first element, move the element at position 1 to position 0, and reduce the size of the array from 2 to 1. In the second iteration, you try to erase an element at position 1, but that is now past the end of the vector!

P.S.: the safe way to erase multiple elements from a vector is starting with the highest position, not the lowest. Alternately, if you wish to erase a range of elements, I believe there is an overload for erase that accepts a range start and range end.
 
Share this answer
 
v2
Comments
CPallini 3-Dec-21 16:36pm    
5.
As Stefan suggested, you may use the erase overload that takes a range (two iterators) as argument. See the code sample here: vector::erase - C++ Reference[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900