Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

remove
c++
communitycreator

How to use the remove() function in C++

Harsh Jain

The remove() function in C++ helps to remove all the occurrences of a value within a specified range.

This function is available in the <algorithm.h> header file.

Parameters

The remove() function accepts the following parameters.

  • first: This is an iterator that points to the first index of the array or vector from where we want to perform the remove operation.

  • last: This is an iterator that points to the last index of the array or vector till where we want to perform the remove operation.

  • value: This is the value that we want to remove within the range [first, last) in the given array or vector.

Return value

The remove() function returns an iterator that points to past the last element that is not removed.

Code

Let’s look at the code below.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {

  vector<int> vec = { 10, 20, 30, 40, 30, 60, 70, 30, 100 };
  auto it = remove(vec.begin(), vec.end(), 30);
  
  for (auto i = vec.begin(); i != it; i++)
    cout << *i << " ";
  
  return 0;
}
Use the remove() function in C++

Explanation

  • From lines 1 to 3, we import the required libraries.

  • In line 8, we create a vector that contains integer values.

  • In line 9, we call the remove() function and pass 30 as the value removed from the vector.

  • In lines 11 and 12, we print the vector values after removing 30 from it. The remove() function returns an iterator that points to past-the-last element not removed. Hence, we need to run the loop till that iterator only.

In this way, we can easily remove all occurrences of a value from a vector within the specified range.

RELATED TAGS

remove
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring