map::clear() in C++ STL
Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key.
map::clear()
clear() function is used to remove all the elements from the map container and thus leaving it’s size 0.
Syntax:
map1.clear() where map1 is the name of the map. Parameters: No parameters are passed.
Return Value: None
Examples:
Input : map1 = < , , , > map1.clear(); Output: map1 = <> Input : map2 = <> map2.clear(); Output: map2 = <>
// CPP program to illustrate
// Implementation of clear() function
using namespace std;
// Take any two maps
map < int , string>map1, map2;
// Inserting values
map1[1] = «India» ;
map1[2] = «Nepal» ;
map1[3] = «Sri Lanka» ;
map1[4] = «Myanmar» ;
// Print the size of map
cout<< "Map size before running function: \n" ;
// Deleting the map elements
// Print the size of map
cout<< "Map size after running function: \n" ;
Map size before running function: map1 size = 4 map2 size = 0 Map size after running function: map1 size = 0 map2 size = 0
Time complexity: Linear i.e. O(n)
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you’re new to coding. Start today and join millions on a journey to improve your skills! Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out — check it out now!
Different ways to delete elements in std::map (erase() and clear())
The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following ways:
A. Remove using the Key
erase (key)
Erases the key-value pair using the key mentioned in its argument. reorders the map after deletion. It returns the number of entries deleted. If non-existing keys is deleted, 0 is returned.
- Time complexity: log(n) (n is size of the map)
B. Remove using Iterator
erase (iter)
Erases the pair at the position pointed by the iterator mentioned in its argument.
C. Remove Elements in a Range
erase (strt_iter, end_iter)
Erases the range of pairs starting from “strt_iter” to the “end_iter”.
- Time complexity:O(k) (where k is the linear distance between strt_iter and end_iter i.e. the number of elements between the given range).
Example
C++
// C++ code to demonstrate the working of erase()
#include
using namespace std;
// declaring map
// of char and int
// declaring iterators
map< char , int >::iterator it;
map< char , int >::iterator it1;
map< char , int >::iterator it2;
// inserting values
// printing initial map elements
cout << "The initial map elements are : \n" ;
for (it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
it = mp.begin();
cout << endl;
// erasing element using iterator
// erases 2nd element
// printing map elements after deletion
cout << "The map elements after 1st deletion are : \n" ;
for (it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
cout << endl;
// erasing element using value
int c = mp.erase( 'c' );
// printing map elements after deletion
cout << "The map elements after 2nd deletion are : \n" ;
for (it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
cout << "The number of elements deleted in 2nd "
"deletion are : " ;
cout << c << endl;
cout << endl;
// erasing element using value
// key not present
int d = mp.erase( 'w' );
// printing map elements after deletion
cout << "The map elements after 3rd deletion are : \n" ;
for (it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
cout << "The number of elements deleted in 3rd "
"deletion are : " ;
cout << d << endl;
cout << endl;
// erasing element using range iterator
// deletes "d" and "e" keys
mp.erase(it, mp.end());
// printing map elements 4th deletion
cout << "The map elements after 4th deletion are : \n" ;
for (it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
cout << endl;
Output
The initial map elements are : a->5 b->10 c->15 d->20 e->30 The map elements after 1st deletion are : a->5 c->15 d->20 e->30 The map elements after 2nd deletion are : a->5 d->20 e->30 The number of elements deleted in 2nd deletion are : 1 The map elements after 3rd deletion are : a->5 d->20 e->30 The number of elements deleted in 3rd deletion are : 0 The map elements after 4th deletion are : a->5
2. Using clear()
The clear function clears all the elements present in the map. After this function is called, the size of map becomes 0.
Syntax
map_name.clear()
Example
CPP
// C++ code to demonstrate the working of clear()
#include
using namespace std;
// declaring map
// of char and int
// declaring iterator
map< char , int >::iterator it;
// inserting values
// printing initial map elements
cout << "The initial map elements are : \n" ;
for ( auto it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
// using clear() to erase all elements in map
// printing map elements after deletion
cout << "The map elements after clearing all elements "
for ( auto it1 = mp.begin(); it1 != mp.end(); ++it1)
cout << it1->first << "->» << it1->second << endl;<>
Output
The initial map elements are : a->5 b->10 c->15 d->20 e->30 The map elements after clearing all elements are :
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you’re new to coding. Start today and join millions on a journey to improve your skills!
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out — check it out now!
What is the most concise way to clear a map and delete contents?
I have a std::list and a std::map that I would like to empty and call delete on all the pointers. After reading this question I am using this for the std::list:
mylist.remove_if([](myThingy* thingy) -> bool < delete thingy; return true; >);
Is there something similarly concise for std::map? Note that I cannot use a range based for loop because it isn’t supported by my compiler (VC10). If it would be possible I assume
for(auto* thingy : myMap) < delete thingy; >myMap.clear();
would work. Please correct me if I am wrong.
1 1 1 silver badge
asked May 3, 2013 at 17:12
6,762 6 6 gold badges 37 37 silver badges 56 56 bronze badges
You really shouldn’t use std::list or std::map for collections of ordinary pointers. You should either use collections designed to hold pointers or use smart pointers. If you do either of those, you can do what you want just by emptying the collection.
May 3, 2013 at 17:14
It’s old code by somebody else, but still, which collections are designed to use pointers?
May 3, 2013 at 17:18
I second Sarien’s question: «Which collections are designed to use pointers?»
May 3, 2013 at 17:29
boost::ptr_container boost.org/doc/libs/1_53_0/libs/ptr_container/doc/reference.html
May 3, 2013 at 17:31
@DavidSchwartz std::map for raw pointers is ubitquitous for navigation purposes. (Here, of course, it is clear that the map should manage the pointers, and `std::shared_ptr would probably be a good idea.)
May 3, 2013 at 17:40
2 Answers 2
Is there something similarly concise for std::map?
You could do it this way (supposing your thingy is the mapped value, and not the key):
for_each(myMap.begin(), myMap.end(), [] (decltype(myMap)::value_type const& p) < delete p.second; >); myMap.clear();
Concerning the range-based for loop:
If it would be possible I assume
for(auto* thingy : myMap) < delete thingy; >myMap.clear();
would work. Please correct me if I am wrong.
More or less. You still need to keep in mind that values of a map are actually pairs — but you could fix the range-based for to keep that into account, yes:
for (auto&& p : myMap) < delete p.second; >myMap.clear();
Anyway, please consider using smart pointers instead of performing manual memory management through raw pointers, new , and delete . This way you would avoid this kind of problems.
1 1 1 silver badge
answered May 3, 2013 at 17:16
Andy Prowl Andy Prowl
125k 24 24 gold badges 388 388 silver badges 452 452 bronze badges
I had to change the lambda to [](std::pair
May 3, 2013 at 17:45
@Sarien: Oh, ok then. VC10 weirdness. You could probably have a typedef std::map
May 3, 2013 at 17:46
I don’t think your remove_if solution is a good idea for the other types, either. Just use a simple loop (or foreach):
for ( auto current = myMap.begin(); current != myMap.end(); ++ current ) < delete current->second; > myMap.clear();
Note that you cannot do a delete current->first ; this will invalidate keys in the map. And unless you are doing a clear() immediately afterwards (or are destructing the map), set the deleted pointer to NULL.
With regards to your second question:
for ( auto* thingy : myMap )
would certainly not work. The value type of map is a pair, not a pointer, so you’ld need somthing like:
for ( auto thingy : myMap )
(I think. I’ve not been able to experiment with this either.)
map erase() function in C++ STL
map::erase() is a built-in function in C++ STL that is used to erase elements from the container. It can be used to erase keys and elements at any specified position or a given range.
map_name.erase(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container.
Return Value: The function returns 1 if the key element is found in the map else returns 0.
The below program illustrate the above syntax:
C++
// C++ program to illustrate
// map::erase(key)
using namespace std;
// initialize container
// insert elements in random order
// prints the elements
cout << "The map before using erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
// function to erase given keys
// prints the elements
cout << "\nThe map after applying erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
Output
The map before using erase() is : KEY ELEMENT 1 40 2 30 3 60 5 50 The map after applying erase() is : KEY ELEMENT 3 60 5 50
Time Complexity: O(log N)
map_name.erase(iterator position)
Parameters: The function accepts one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased.
Return Value: The function does not return anything.
The below program illustrate the above syntax:
C++
// C++ program to illustrate
// map::erase(iteratorposition)
using namespace std;
// initialize container
// insert elements in random order
// prints the elements
cout << "The map before using erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
// function to erase given position
auto it = mp.find(2);
auto it1 = mp.find(5);
mp.erase(it1);
// prints the elements
cout << "\nThe map after applying erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
Output
The map before using erase() is : KEY ELEMENT 1 40 2 30 3 60 5 50 The map after applying erase() is : KEY ELEMENT 1 40 3 60
Time Complexity: O(N) or Amortized constant
map_name.erase(iterator position1, iterator position2)
Parameters: The function accepts two mandatory parameters which are described below:
- position1 – specifies the iterator that is the reference to the element from which removal is to be done.
- position2 – specifies the iterator that is the reference to the element up to which removal is to be done.
Return Value: The function does not return anything. It removes all the elements in the given range of iterators.
The program below illustrates the above syntax:
C++
// C++ program to illustrate
// map::erase(iteratorposition1, iteratorposition2)
using namespace std;
// initialize container
// insert elements in random order
// prints the elements
cout << "The map before using erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
// function to erase in a given range
// find() returns the iterator reference to
// the position where the element is
auto it1 = mp.find(2);
auto it2 = mp.find(5);
mp.erase(it1, it2);
// prints the elements
cout << "\nThe map after applying erase() is : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin(); itr != mp.end(); ++itr) <
cout << itr->first<>
Output
The map before using erase() is : KEY ELEMENT 1 40 2 30 3 60 5 50 The map after applying erase() is : KEY ELEMENT 1 40 5 50
Time Complexity: O(last – first)
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you’re new to coding. Start today and join millions on a journey to improve your skills!
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out — check it out now!