C++ Erase Function Explained

In C++, the erase() function is used to remove one or more elements from a container.

The erase() function has multiple use cases:

  1. Delete a single element: You can use the erase() function to remove a single element by specifying its position or iterator.
  2. For the vector container, you can use the following code to delete the element at position i.
  3. Remove element at index i from myVector.
  4. Alternatively, you can use iterators to remove elements.
  5. Erase the element in myVector at index i.
  6. Delete elements within a range: By specifying the range of elements to be deleted, the erase() function can be used to remove elements within that range.
  7. For example, to remove elements from position i to j in a vector container, you can use the following code:
  8. Remove elements from the vector “myVector” starting at index “i” up to index “j” (inclusive).
  9. Alternatively, you can use an iterator to remove elements within a range.
  10. Delete elements in the vector, starting at index i and ending at index j.
  11. Remove elements that meet certain conditions: You can use the erase() function to delete elements that meet a specific predicate.
  12. For vector containers, you can use the following code to remove all elements that are equal to a specific value:
  13. Remove the value 3 from the vector.
  14. The std::remove() function in the above code will move elements equal to a specific value to the end of the container, and then the erase() function will delete these elements.

It’s important to note that the erase() function is only applicable to containers that can be accessed using iterators, such as vectors, lists, sets, etc. For associative containers like maps and unordered_maps, specific deletion functions like erase() or erase_if() need to be used.

bannerAds