C++ Map Erase Function - C++ Programming Tutorial
C++ Course / STL Set & Map / C++ Map Erase Function

C++ Map Erase Function

BLUF: Mastering C++ Map Erase Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Map Erase Function

C++ is renowned for its efficiency. Learn how C++ Map Erase Function enables low-level control and high-performance computing in the tutorial below.

In C++, the Standard Template Library (STL) offers a robust set of data structures and algorithms for developers to utilize. Within the STL, the map serves as a prevalent associative container. It stores elements in key-value pairs, ensuring that keys are distinct and arranged in order based on the specified comparator function.

In C++, the erase method in the map container is a predefined function. It is frequently used to delete either a specific element linked to a provided key value or a set of elements from the map container. As a result, the size of the map will decrease by the quantity of elements that have been deleted.

Syntax:

It has the following syntax:

Example

void erase (iterator position);                           //until C++ 11  

size_type erase (const key_type& k);              //until C++ 11  

void erase (iterator first, iterator last);           //until C++ 11  

iterator  erase (const_iterator position);        //since C++ 11  

size_type erase (const key_type& k);          //since C++ 11      

iterator  erase (const_iterator first, const_iterator last); //since C++ 11

In this syntax,

  • position: It is used to represent an iterator pointing to a single element to be removed from the map.
  • k: It is used to represent a key of the element to be removed from the map.
  • first: It represents the beginning of the range to erase.
  • last: It represents the ending of the range to erase.
  • Return value

It returns an iterator pointing to the next element after the deleted element or returns the count of deleted elements.

Simple map empty function in C++

Let's consider a basic scenario where we remove the element through iteration using the empty function within the map container in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;    //using standard namespace

  

int main ()    //main function

{  

  map<char,int> mymap;  

  map<char,int>::iterator it;  

  mymap['a']=10;  

  mymap['b']=20;  

  mymap['c']=30;  

  mymap['d']=40;  

    

  cout<<"Before erasing the element: \n";  

   for (it=mymap.begin(); it!=mymap.end(); ++it)  

  std::cout << it->first << " => " << it->second << '\n';  

  it=mymap.find('b');  

  mymap.erase (it);                   // erasing by iterator  

  

  cout<<"\nAfter erasing the element: \n";  

  for (it=mymap.begin(); it!=mymap.end(); ++it)  

    std::cout << it->first << " => " << it->second << '\n';  

  return 0;  

}

Output:

Output

Before erasing the element:

a => 10

b => 20

c => 30

d => 40

After erasing the element:

a => 10

c => 30

d => 40

Explanation:

In this instance, a map named mymap has been established to hold character keys and their corresponding integer values. Subsequently, the erase method is employed to eliminate a particular element from the map by utilizing an iterator acquired through the find method. Following the erasure process, the map's elements are showcased to illustrate the modification. Ultimately, the map::erase function effectively eliminates a key-value pair while preserving the map's sorted sequence.

C++ Example to erase an element from a map using a key

Let's consider a scenario where we want to remove the entry from the map by specifying its key value utilizing the erase function in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;    //using standard namespace

int main ()    //main function

{  

  map<char,int> mymap;  

  map<char,int>::iterator it;  

  

  mymap['a']=10;  

  mymap['b']=20;  

  mymap['c']=30;  

  mymap['d']=40;  

    

  cout<<"Before erasing the element: \n";  

   for (it=mymap.begin(); it!=mymap.end(); ++it)  

    std::cout << it->first << " => " << it->second << '\n';  

  

 mymap.erase ('c');                  // erasing by key  

  

  cout<<"\nAfter erasing the element: \n";  

  for (it=mymap.begin(); it!=mymap.end(); ++it)  

    std::cout << it->first << " => " << it->second << '\n';  

  return 0;  

}

Output:

Output

Before erasing the element:

a => 10

b => 20

c => 30

d => 40

After erasing the element:

a => 10

b => 20

d => 40

Explanation:

In this instance, a map titled mymap has been established to hold integer values associated with character keys. Subsequently, the erase method is employed to eliminate the element linked to the key 'c' from the map. Following the deletion process, all elements within the map are exhibited to demonstrate the modification. Lastly, the erase function is utilized to eliminate a particular key-value pair while preserving the map's ordered arrangement.

C++ Example to erase a range of elements from a map using the map erase function

Let's consider a scenario where we want to remove a specific range of elements from a map by utilizing the map's erase function in C++.

Example

Example

#include <iostream>  

#include <map>  

  

using namespace std;   //using standard namespace

  

int main ()    //main function

{  

  map<char,int> mymap;  

  map<char,int>::iterator it;  

  

  mymap['a']=10;  

  mymap['b']=20;  

  mymap['c']=30;  

  mymap['d']=40;  

    

  cout<<"Before erasing, the elements are: \n";  

   cout<<"Size is: "<<mymap.size()<<'\n';  

   for (it=mymap.begin(); it!=mymap.end(); ++it)  

   cout << it->first << " => " << it->second << '\n';  

  

   mymap.erase ( mymap.begin () ,  mymap.end () );   // erasing by range  

  

  cout<<"\nAfter erasing, the elements are: \n";  

  cout<<"Size is: "<<mymap.size();  

  for (it=mymap.begin(); it!=mymap.end(); ++it)  

  cout << it->first << " => " << it->second << '\n';  

  return 0;  

}

Output:

Output

Before erasing, the elements are:

Size is: 4

a => 10

b => 20

c => 30

d => 40

After erasing, the elements are:

Size is: 0

Explanation:

In this instance, we've established a map called mymap that is employed for holding character keys and corresponding integer values. Subsequently, the erase method is employed with a set of iterators to eliminate all entries from the map simultaneously. Preceding and following the deletion operations, the size and contents of the map are showcased to demonstrate the modification. Ultimately, executing erase(begin, end) effectively eliminates all key-value pairs from the map and showcases the result.

C++ Example to erase Elements Conditionally from a Map using the map erase function

Let's consider a straightforward scenario where we remove all the odd numbers from a map using the erase function in C++.

Example

Example

#include <map>  

#include <iostream>  

using namespace std;    //using standard namespace

int main()    //main function

{  

    map<int, string> m = {{1, "one"},   

                          {2, "two"},   

                          {3, "three"},  

                          {4, "four"},   

                          {5, "five"},   

                          {6, "six"}};  

                            

    // erase all odd numbers from m  

    cout<<"After erasing odd numbers, the elements are:\n ";  

    for(auto it = m.begin(); it != m.end(); )  

        if(it->first % 2 == 1)  

            it = m.erase(it);  

        else  

            ++it;  

    for(auto& p : m)  

        cout << p.second << ", ";  

}

Output:

Output

After erasing odd numbers, the elements are:

two, four, six,

Explanation:

In this instance, we have established a dictionary that is frequently employed for holding integer keys alongside their associated string values. Subsequently, we employ the erase method within a loop to eliminate all entries with odd keys from the dictionary. The iterator is carefully handled to prevent invalidation following each deletion process. To conclude, it demonstrates the selective removal of entries from a dictionary based on particular conditions by utilizing the erase method.

Features of the map erase function in C++

There are several features of the map erase function in C++. Some of them are as follows:

  • In C++, the map erase function is commonly utilized to erase one or multiple key-value pairs from a map container.
  • We can delete the element using the map erase function in three ways: by key, iterator, or by range of iterators. It provides us with better flexibility in the program.
  • When an element is deleted from the map container, its memory is automatically deallocated by the map, which helps to make sure that it has no memory leak.
  • The map erase function provides safety and ensures that no other elements are disturbed during the erasing operation. It takes a complexity of O(log N) for a single deletion operation.
  • When we erase the element from the map container using the erase function, the map automatically maintains its sorted order, which is based on the keys.
  • If the iterators point to the erased or deleted elements, they become invalid. On the other hand, other iterators remain valid and unchanged.
  • Conclusion

In summary, the erase function in C++ for maps is a fundamental and straightforward approach to remove elements from the map container. It allows us to eliminate elements through key, iterator, or range-based methods, offering increased versatility and precision in data manipulation. By utilizing the erase function, the map's sorted arrangement is preserved automatically during deletion, promoting secure memory management. This function's efficiency and ease of use facilitate seamless modifications to map data, ensuring program stability and data integrity are upheld.

C++ Map erase function FAQs

The primary objective of the map erase function in C++ is to remove a specific element from a map container.

In C++, the erase method in the map container is an inherent member function. It is frequently used to eliminate either a specific element linked to a provided key value or a series of elements from the map container.

There are various techniques to utilize the erase function of the map container in C++:

  • Using an iterator to specify the element to erase
  • Providing a key value to remove a specific element from the map
  • Erasing a range of elements by defining a beginning and ending iterator positions

In C++ programming, there are mainly three methods by which the map erase method can be utilized:

  • By Keys: It is used to remove the elements using the key.
  • By Iterator: It is used to remove the elements using a definite iterator position.
  • By Range of Elements: It is used to remove the range of elements.

No, the erase function in C++ does not maintain the sorted order after deletion.

Yes, if the element is removed using the erase function, the map will automatically rearrange its sequence according to the keys or elements.

When iterators are used after employing the map erase function in C++, it can lead to undefined behavior. This is because erasing elements from a map invalidates iterators pointing to the erased elements, which can cause issues when attempting to access or iterate through the map. It is essential to be cautious and avoid using invalidated iterators to prevent unexpected results in the program.

In C++, when iterators point to elements that have been erased or deleted, they become invalid. Nonetheless, the rest of the iterators remain valid and unchanged.

5) What is the return value of the erase function in C++ maps?

When removing elements in C++ with the key method, the function will return the count of removed elements. Conversely, erasing elements using an iterator, a range, or specific elements will result in a void return type.

6) Is it permissible to utilize the erase function of the map container within a loop in C++?

Yes, it is possible to utilize the map erase function within a loop in C++. Nonetheless, it is crucial to manage the iterator efficiently. When removing or erasing an element from the map using an iterator, the iterator's reference to that specific element becomes invalid.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience