0

//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;
}
nzaw96
  • 1

1 Answers1

1
  while(i < v.size()-1){
    v[i] = v[i+1];
  }

Since nowhere here i gets incremented, the conclusion is inevitable: if at the beginning i is less than v.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 than v.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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Hi, thanks for your help. I missed that glaringly obvious bug there. Also would you mind naming the other bugs that you saw? I'm a beginner so the more feedback I get, the faster I learn. – nzaw96 Apr 14 '20 at 16:57
  • If you have a vector with just two values `{2,2}`, and the value to remove is also `2` (remove all `2`s from the vector), the expected result is an empty vector, since all values are removed. The above code should end up failing to remove one of the two values, resulting in a vector containing a single `{2}`. If the original vector had `{1,2,2,3}`, one of the `2`s will also not be removed, resulting in the final vector containing `{1,2,3}`. Use your debugger to figure out why. This is what a debugger is for. – Sam Varshavchik Apr 14 '20 at 18:07