//this function is takes in two arguments, a vector of type Vec and an element of type T, and returns //the number of elements that matched the argument and were successfully removed from the vector. The //order of the other elements should stay the same.
//I've added this to the .h file and tried to call this function from a test.cpp file with the lines:
int num_ele = remove_matching_elements(v, 22);
cout << num_ele << endl;
//where v is {11, 22, 33, 11, 55, 33}
template <class T> int remove_matching_elements(Vec<T>& v, const T& t) {
int counter = 0;
int i;
for(i = 0; i < v.size(); i++){
if(v[i] == t){
counter++;
while(i < v.size()-1){
v[i] = v[i+1];
}
v.resize(v.size()-1,0);
}
}
return counter;
}
Since nowhere here
i
gets incremented, the conclusion is inevitable: if at the beginningi
is less thanv.size()-1
, it will remain, as such, forever, until our sun burns out, resulting in an infinite loop:i
never changes here, so it remains forever less thanv.size()-1
. And that's why you get no output.This does not seem to be the only bug. The shown algorithm appears to be flawed in at least one other way, and will not reliably remove duplicates, in at least one edge case. But that would be a different question.
The C++ library has several algorithm functions that make it possible to do all of this in one line; but I presume that this is a class assignment to do it manually. You should rethink your approach to be iterator-based, which will make this implementation much simpler and reliable.