Vector-Erase in C++ hackerrank solution

Problem statement:


You are given a vector of integers and two queries. The first query is to erase a specific element from the vector, and the second query is to erase a range of elements from the vector.

Your task is to write a program that performs these operations and prints the resulting vector after each query.

      

Sample Input:

The input consists of three lines:

The first line contains an integer n, representing the number of elements in the vector.

The second line contains n space-separated integers, representing the elements of the vector.

The third line contains two integers x and a, representing the element to be erased and the range of elements to be erased, respectively.


6 1 4 6 2 8 9 2 2
      

Sample Output:

Print the elements of the vector after each query on a new line.
1 4 6 8 9

Explanation:

In this example, we have a vector initially containing the elements 1 4 6 2 8 9. After the first query, the element 2 is erased from the vector, resulting in 1 4 6 8 9. After the second query, the elements in the range [2, 2] are erased, which corresponds to the element at index 2 (6), resulting in 1 4 8 9.

      
  #include <iostream>
  #include <vector>  
  using namespace std;
  
  int main() {
      int n;
      cin >> n;
      
      vector v(n);
      
      for (int i = 0; i < n; i++) {
          cin >> v[i];
      }
      
      int x, a;
      cin >> x >> a;
      
      v.erase(v.begin() + x - 1);
      v.erase(v.begin() + a - 1, v.begin() + a);
      
      cout << v.size() << endl;
      
      for (int i = 0; i < v.size(); i++) {
          cout << v[i] << " ";
      }
      
      return 0;
  }
  

Code Explanation


We start by including the necessary header files, including for input/output operations and for using the vector container.

In the main() function, we read the number of elements in the vector (n) using cin.

We create a vector v of integers with size n.

Using a loop, we read the elements of the vector and store them in v.

We then read the element to be erased (x) and the range of elements to be erased (a) using cin.

To perform the queries, we use the erase() function of the vector container. The first query erases the element at index x-1, and the second query erases the elements in the range [a-1, a). Note that we subtract 1 from the indices to account for 0-based indexing.

After performing the queries, we print the size of the vector (v.size()) to indicate the number of remaining elements.

Finally, we use a loop to print the elements of the vector separated by a space.

The solution handles input based on the given format, performs the required queries using the erase() function, and provides the expected output as specified in the problem statement.

I hope this explanation helps! Let me know if you have any further questions.