Logic error using .erase (C++) -
so program reading input of numbers , lists them in order. seen in output. without use of algorithm library, sorted , getting rid of repeated data. however, if there data value repeated, last value of vector not printed. incorrectly using .erase?
void remove_repeated(int size, vector<int>& num_vec){ for(int = 0; < num_vec.size(); i++){ if(num_vec[i]==num_vec[i+1]){ num_vec.erase((num_vec.begin()+i)); } } }
output when no value repeated:
**welcome hw reading program** please, enter hw:1-10 problems: 1, 2, 3, 4, 5, 6, 7, 8, 9,and 10
output when value repeated:
**welcome hw reading program** please, enter hw: 1-10,1-3 problems: 1, 2, 3, 4, 5, 6, 7, 8,and 9
after erase element @ index i
vector, next element @ index i
, not @ index i+1
. have take care not go out of bounds when comparing i+1
, ie loop has this:
for(int = 0; < num_vec.size()-1;){ if(num_vec[i]==num_vec[i+1]){ num_vec.erase((num_vec.begin()+i)); } else { i++; } }
also should consider use standard library has offer. set
contains unique elements, or can use erase
+unique
(see eg. here more details).
Comments
Post a Comment