Removal Algorithms

Remove Elements Without Surplus

How can I remove elements from a container without leaving surplus elements at the end?

Abstract art representing computer programming

When using algorithms like std::remove() or std::remove_if() from the C++ Standard Library, the elements to be removed are shifted to the end of the container, but the container's size remains unchanged.

To fully remove these elements and adjust the container size, you can use the remove-erase idiom.

Here's how you can do it:

  1. Apply the std::remove() or std::remove_if() algorithm to shift the unwanted elements to the end.
  2. Use the container's erase() method to remove the surplus elements.

For example, let's remove all occurrences of the number 3 from a std::vector:

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

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

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

  // Step 2: Erase surplus elements
  Source.erase(NewEnd, Source.end());

  // Display the result
  std::cout << "Objects in Source: ";
  for (auto Num : Source) {
    std::cout << Num << ", ";
  }
}
Objects in Source: 1, 2, 4, 5, 6,

The std::remove() function reorders the container so that all elements not equal to 3 are moved to the front, and the erase() method removes the unwanted surplus elements from the end.

This method is efficient and commonly used in C++ to manage container sizes properly after removal operations.

Remember, the same concept can be applied to other containers like std::deque or std::list by using their respective erase() methods.

This Question is from the Lesson:

Removal Algorithms

An overview of the key C++ standard library algorithms for removing objects from containers. We cover remove(), remove_if(), remove_copy(), and remove_copy_if().

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

This Question is from the Lesson:

Removal Algorithms

An overview of the key C++ standard library algorithms for removing objects from containers. We cover remove(), remove_if(), remove_copy(), and remove_copy_if().

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:

  • 125 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