C++ Map – Erasing Elements By Callback
Last Updated :
01 Dec, 2022
Prerequisite: Maps
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Different ways to erase elements in Map are:
- Erase by key
- Erase by position
- Erase by value
- Erase by Callback
What are Callback or Callback functions?
A callback is any executable code that is passed as an argument to another code, which is expected to call back (execute) the argument at a given time. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called a Callback function.
Approach: Iterate over all the elements of the map and execute the given callback for each element. If the callback returns true then delete that element and move to the next element.
Example:
C++
#include <iostream>
#include <map>
using namespace std;
template < typename key, typename value>
void erase_odd(map<key, value>& mp, bool (*functor)(key))
{
auto it = mp.begin();
while (it != mp.end()) {
if (functor(it->first)) {
it = mp.erase(it);
}
else {
it++;
}
}
}
bool call_back( int val)
{
if (val % 2 != 0) {
return true ;
}
return false ;
}
int main()
{
map< int , int > gfg;
gfg[1] = 2;
gfg[2] = 5;
gfg[3] = 3;
gfg[4] = 6;
gfg[5] = 8;
gfg[6] = 9;
cout << "Original Map\n" ;
cout << "\tKEY\tELEMENT\n" ;
for ( auto i : gfg) {
cout << '\t' << i.first << '\t' << i.second << '\n' ;
}
erase_odd(gfg, &call_back);
cout << "Map After passing it and a callback to "
"erase_odd function\n" ;
cout << "\tKEY\tELEMENT\n" ;
for ( auto i : gfg) {
cout << '\t' << i.first << '\t' << i.second << '\n' ;
}
return 0;
}
|
Output
Original Map
KEY ELEMENT
1 2
2 5
3 3
4 6
5 8
6 9
Map After passing it and a callback to erase_odd function
KEY ELEMENT
2 5
4 6
6 9
Explanation:
- Firstly we define a function with a return datatype void and it takes a map<int, int> by reference and a callback function.
- This function deletes the keys for which the callback function returns true.
- Then we define a call_back function that returns true if the passed value is odd otherwise it returns false.
- After this, inside the main function, we declare a map<int, int>.
- Then we insert some dummy data in the map.
- Then we print the original map that we have created.
- Now we have passed the map and callback function to the erase_odd function.
- Finally, we print the map.
Share your thoughts in the comments
Please Login to comment...