Search code examples
c++vectorerase

erasing elements from a vector (hackerrank)


I'm a beginner in C++. I have tried to solve this problem but couldn't, thus I checked the solution afterwards but there are some lines I don't understand:

v.erase(v.begin() + x - 1); // i want to know why the "-1" is put here
v.erase(v.begin() + b - 1, v.begin() + c - 1);

Here is the code:

int main()
{
  int N, a, x, b, c;
  vector <int> v;
  cin >> N;
  for (int i = 0; i<N; i++)
  {
    cin >> a;
    v.push_back(a);
  }
  cin >> x >> b >> c;
  v.erase(v.begin() + x - 1);
  v.erase(v.begin() + b - 1, v.begin() + c - 1);
  cout << v.size() << endl;
  for (int i = 0; i < v.size(); i++)
  {
    cout << v[i] << " ";
  }
}

Solution

  • The question aims to make you familiar with 2 common syntax of vector erase method . For deleting single element use ,

    v.erase( pass iterator pointing to the element that you want to erase)

    For example , v.erase(v.begin()) will erase first element of the vector or in other words will erase element at position 0 of the vector.

    Since here v.begin() is iterator to the first element of the vector , provided vector isn't empty .

    Similarly ,

    v.erase(v.begin() + x -1);
    

    erases element at position x of the vector.

    Now to erase a range in the vector , overloaded method of erase is used . It is used as follows ,

    v.erase(iter1,iter2)

    It will erase all the elements in the range of iter1 to iter2 but not including iter2 , that is elements in the range [iter2 , iter2) will be erased . Remember iter2 won't be erased . Thus this code ,

    v.erase(v.begin() + b - 1, v.begin() + c - 1);
    

    will erase all the elements from index b to index c , but not including index c .