Removal Algorithms

Remove and Erase in std::map

How do I remove elements from a std::map using the remove-erase idiom?

Abstract art representing computer programming

The remove-erase idiom typically applies to sequence containers like std::vector, but you can adapt similar concepts to associative containers like std::map.

However, since std::remove() doesn’t directly apply to std::map, you need to use a different approach.

For std::map, you can achieve element removal based on a condition using a loop and the erase() method. Here’s how to do it:

  1. Iterate over the map.
  2. Use the erase() method to remove elements that match a condition.

Here's an example to remove entries with values less than 3 from a std::map<int, int>:

#include <iostream>
#include <map>

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

  // Iterating and removing elements based on a condition
  for (auto it = Source.begin(); it != Source.end();) {
    if (it->second < 3) {
      it = Source.erase(it); 
    } else {
      ++it;
    }
  }

  // Display the result
  std::cout << "Elements in Source: ";
  for (const auto& Pair : Source) {
    std::cout << "{" << Pair.first << ", "
              << Pair.second << "}, ";
  }
}
Elements in Source: {2, 3}, {4, 4},

In this example:

  • We iterate over the Source map.
  • We use erase(it) to remove elements that match the condition (it->second < 3), and adjust the iterator accordingly.

This approach is efficient and ensures that all matching elements are removed from the std::map.

The erase() method is crucial here because it adjusts the container's size and ensures memory is managed correctly.

While this isn’t the traditional remove-erase idiom, it achieves the same goal for associative containers like std::map. Remember to handle the iterator properly after calling erase() to avoid invalid iterator issues.

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