Removal Algorithms

Remove vs Erase

What is the difference between std::remove() and std::erase() in C++?

Abstract art representing computer programming

The difference between std::remove() and std::erase() is crucial in understanding how to manipulate containers effectively in C++.

std::remove() is an algorithm found in the <algorithm> header. It does not change the size of the container but reorders the elements such that the elements to be "removed" are moved to the end.

It returns an iterator to the new end of the range, beyond which the elements are considered to be removed. However, the container itself still holds those elements.

On the other hand, erase() is a member function of containers like std::vector, std::list, and std::deque. It actually removes elements from the container and adjusts the container's size accordingly.

Here's an example to illustrate the difference:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> Source{1, 2, 3, 4, 5, 3, 6};

  // Using std::remove()
  auto NewEnd = std::remove(Source.begin(),
    Source.end(), 3);

  std::cout << "After std::remove(): ";
  for (auto it = Source.begin();
    it != Source.end(); ++it) {
    std::cout << *it << ", ";
  }
  std::cout << "\nSize after std::remove(): "
    << Source.size() << "\n";

  // Using erase() to actually remove the elements
  Source.erase(NewEnd, Source.end());

  std::cout << "After erase(): ";
  for (auto Num : Source) {
    std::cout << Num << ", ";
  }
  std::cout << "\nSize after erase(): "
    << Source.size() << "\n";
}
After std::remove(): 1, 2, 4, 5, 6, 3, 6,
Size after std::remove(): 7
After erase(): 1, 2, 4, 5, 6,
Size after erase(): 5

In the example above:

  • std::remove() moves the 3s to the end and returns an iterator to the new end, but the size of Source remains unchanged.
  • erase() then actually removes the surplus elements and updates the container size.

Understanding the distinction between these two functions is critical for effective container management in C++.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved