Map in C++ Standard Template Library (STL)

Map in C++ Standard Template Library (STL)

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 same key values.  map 是关联式容器,每个元素由一个key和对应的value。没有两个value对应同样的key。

Some basic functions associated with Map:
begin() – Returns an iterator to the first element in the map
end() – Returns an iterator to the theoretical element that follows last element in the map
size() – Returns the number of elements in the map
max_size() – Returns the maximum number of elements that the map can hold
empty() – Returns whether the map is empty
pair insert(keyvalue, mapvalue) – Adds a new element to the map
erase(iterator position) – Removes the element at the position pointed by the iterator
erase(const g)– Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map

#include <iostream> 
#include <iterator> 
#include <map> 

using namespace std; 

int main() 
{ 

	// empty map container 
	map<int, int> gquiz1; 

	// insert elements in random order 
	gquiz1.insert(pair<int, int>(1, 40)); 
	gquiz1.insert(pair<int, int>(2, 30)); 
	gquiz1.insert(pair<int, int>(3, 60)); 
	gquiz1.insert(pair<int, int>(4, 20)); 
	gquiz1.insert(pair<int, int>(5, 50)); 
	gquiz1.insert(pair<int, int>(6, 50)); 
	gquiz1.insert(pair<int, int>(7, 10)); 

	// printing map gquiz1 
	map<int, int>::iterator itr; 
	cout << "\nThe map gquiz1 is : \n"; 
	cout << "\tKEY\tELEMENT\n"; 
	for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { 
		cout << '\t' << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 
	cout << endl; 

	// assigning the elements from gquiz1 to gquiz2 
	map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); 

	// print all elements of the map gquiz2 
	cout << "\nThe map gquiz2 after"
		<< " assign from gquiz1 is : \n"; 
	cout << "\tKEY\tELEMENT\n"; 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
		cout << '\t' << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 
	cout << endl; 

	// remove all elements up to 
	// element with key=3 in gquiz2 
	cout << "\ngquiz2 after removal of"
			" elements less than key=3 : \n"; 
	cout << "\tKEY\tELEMENT\n"; 
	gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
		cout << '\t' << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 

	// remove all elements with key = 4 
	int num; 
	num = gquiz2.erase(4); 
	cout << "\ngquiz2.erase(4) : "; 
	cout << num << " removed \n"; 
	cout << "\tKEY\tELEMENT\n"; 
	for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 
		cout << '\t' << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 

	cout << endl; 

	// lower bound and upper bound for map gquiz1 key = 5 
	cout << "gquiz1.lower_bound(5) : "
		<< "\tKEY = "; 
	cout << gquiz1.lower_bound(5)->first << '\t'; 
	cout << "\tELEMENT = "
		<< gquiz1.lower_bound(5)->second << endl; 
	cout << "gquiz1.upper_bound(5) : "
		<< "\tKEY = "; 
	cout << gquiz1.upper_bound(5)->first << '\t'; 
	cout << "\tELEMENT = "
		<< gquiz1.upper_bound(5)->second << endl; 

	return 0; 
} 

Output:

The map gquiz1 is : 
	KEY	ELEMENT
	1	40
	2	30
	3	60
	4	20
	5	50
	6	50
	7	10


The map gquiz2 after assign from gquiz1 is : 
	KEY	ELEMENT
	1	40
	2	30
	3	60
	4	20
	5	50
	6	50
	7	10


gquiz2 after removal of elements less than key=3 : 
	KEY	ELEMENT
	3	60
	4	20
	5	50
	6	50
	7	10

gquiz2.erase(4) : 1 removed 
	KEY	ELEMENT
	3	60
	5	50
	6	50
	7	10

gquiz1.lower_bound(5) : 	KEY = 5		ELEMENT = 50
gquiz1.upper_bound(5) : 	KEY = 6		ELEMENT = 50

List of all functions of Map:

map insert() in C++ STL

The map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the map container.

  1. Syntax:
    iterator map_name.insert({key, element})
    

    Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the map container. The function does not insert the key and element in the map if the key already exists in the map.

    Return Value: The function returns an iterator pointing to the new element in the container.

    Below is the illustration of the above syntax:

// C++ program to illustrate 
// map::insert({key, element}) 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 60 }); 

	// does not inserts key 2 with element 20 
	mp.insert({ 2, 20 }); 
	mp.insert({ 5, 50 }); 

	// prints the elements 
	cout << "KEY\tELEMENT\n"; 
	for (auto itr = mp.begin(); itr != mp.end(); ++itr) { 
		cout << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

Output:

KEY    ELEMENT
1    40
2    30
3    60
5    50
  1. Syntax:
    iterator map_name.insert(iterator position, {key, element})
    

    Parameters: The function accepts two parameters which is described below:

    Return Value: The function returns an iterator pointing to the new element in the container.

    Below is the illustration of the above syntax:

    • {key, element}: This specifies a pair that consists of a key and element which is to be inserted into the map container.
    • position: This does not specify the position where the insertion is to be done, it only points to a position from where the searching operation for insertion is to be started to make the process faster. The insertion is done according to the order which is followed by the map container.
// C++ program to illustrate 
// map::insert({key, element}) 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 

	auto it = mp.find(2); 

	// inserts {3, 6} starting the search from 
	// position where 2 is present 
	mp.insert(it, { 3, 60 }); 

	// prints the elements 
	cout << "KEY\tELEMENT\n"; 
	for (auto itr = mp.begin(); itr != mp.end(); ++itr) { 
		cout << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

Output:

KEY    ELEMENT
1    40
2    30
3    60
  1. Syntax:
    iterator map_name.insert(iterator position1, iterator position2)
    

    Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another map container.

    Return Value: The function returns an iterator pointing to the new element in the container.

    Below is the illustration of the above syntax:

// C++ program to illustrate 
// map::insert({key, element}) 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp, mp1; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 

	// inserts all elements in range 
	// [begin, end) in mp1 
	mp1.insert(mp.begin(), mp.end()); 

	// prints the elements 
	cout << "Elements in mp1 are\n"; 
	cout << "KEY\tELEMENT\n"; 
	for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) { 
		cout << itr->first 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

Output:

Elements in mp1 are
KEY    ELEMENT
1    40
2    30

map count() function in C++ STL

The map::count() is a built-in function in C++ STL which returns 1 if the element with key K is present in the map container. It returns 0 if the element with key K is not present in the container. 如果key在map中返回1,否则返回0.

Syntax:

map_name.count(key k)

Parameters: The function accepts a mandatory parameter k which specifies the key to be searched in the map container.

Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.

Below program illustrates the above function:

// C++ program to illustrate 
// the map::count() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 60 }); 
	mp.insert({ 4, 20 }); 
	mp.insert({ 5, 50 }); 

	// checks if key 1 is present or not 
	if (mp.count(1)) 
		cout << "The key 1 is present\n"; 
	else
		cout << "The key 1 is not present\n"; 

	// checks if key 100 is present or not 
	if (mp.count(100)) 
		cout << "The key 100 is present\n"; 
	else
		cout << "The key 100 is not present\n"; 

	return 0; 
} 

Output:

The key 1 is present
The key 100 is not present

map find() function in C++ STL

The map::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end().   在map中查找key的元素,返回该元素的迭代器。

Syntax:

iterator map_name.find(key)
        or 
constant iterator map_name.find(key)

Parameters: The function accepts one mandatory parameter key which specifies the key to be searched in the map container.

Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end().

Below is the illustration of above fucntion:

// C++ program for illustration 
// of map::find() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	multimap<int, int> mp; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 20 }); 
	mp.insert({ 4, 50 }); 

	cout << "The elements from position 3 in map are : \n"; 
	cout << "KEY\tELEMENT\n"; 

	// find() function finds the position at which 3 is 
	for (auto itr = mp.find(3); itr != mp.end(); itr++) 
		cout << itr->first 
			<< '\t' << itr->second << '\n'; 

	return 0; 
} 

Output:

The elements from position 3 in map are : 
KEY    ELEMENT
3    20
4    50

map emplace() in C++ STL

The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container. It effectively increases the container size by one. If the same key is emplaced more than once, the map stores the first element only as the map is a container which does not store multiple keys of the same value.

Syntax:

map_name.emplace(key, element)

Parameters: The function accepts two mandatory parameters which are described below:

  • key – specifies the key to be inserted in the multimap container.
  • element – specifies the element to the key which is to be inserted in the map container.

Return Value: The function does not return anything.

// C++ program for the illustration of 
// map::emplace() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 

	// insert elements in random order 
	mp.emplace(2, 30); 
	mp.emplace(1, 40); 
	mp.emplace(2, 20); 
	mp.emplace(1, 50); 
	mp.emplace(4, 50); 

	// prints the elements 
	cout << "\nThe map is : \n"; 
	cout << "KEY\tELEMENT\n"; 
	for (auto itr = mp.begin(); itr != mp.end(); itr++) 
		cout << itr->first << "\t" << itr->second << endl; 

	return 0; 
} 

Output:

The map is : 
KEY    ELEMENT
1    40
2    30
4    50

map::empty() in C++ STL

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 same key values.

map::empty()

empty() function is used to check if the map container is empty or not. 判断容器是否为空。

Syntax :

mapname.empty()
Parameters :
No parameters are passed.
Returns :
True, if map is empty
False, Otherwise

Examples:

Input  : map 
         mymap['a']=10;
         mymap['b']=20;
         mymap.empty();
Output : False

Input  : map 
         mymap.empty();
Output : True

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// Non Empty map example 
// CPP program to illustrate 
// Implementation of empty() function 
#include <iostream> 
#include <map> 
using namespace std; 

int main() 
{ 
	map<char, int> mymap; 
	mymap['a'] = 1; 
	mymap['b'] = 2; 
	if (mymap.empty()) { 
		cout << "True"; 
	} 
	else { 
		cout << "False"; 
	} 
	return 0; 
} 

Output:

False
// Empty map example 
// CPP program to illustrate 
// Implementation of empty() function 
#include <iostream> 
#include <map> 
using namespace std; 

int main() 
{ 
	map<char, int> mymap; 
	if (mymap.empty()) { 
		cout << "True"; 
	} 
	else { 
		cout << "False"; 
	} 
	return 0; 
} 

Output:

True

map::begin() and end() in C++ STL

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 same key values.

map::begin()

begin() function is used to return an iterator pointing to the first element of the map container. begin() function returns a bidirectional iterator to the first element of the container. begin返回指向map容器的第一个元素的迭代器。

Syntax :

mapname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.

Examples:

Input  : mymap['a'] = 1;
         mymap['b'] = 2;
         mymap['c'] = 3;
         mymap.begin();
Output : returns an iterator to the element 'a' = 1

Input  : mymap['d'] = 1;
         mymap.begin();
Output : returns an iterator to the element 'd' = 1

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <map> 
using namespace std; 

int main() 
{ 
	// declaration of map container 
	map<char, int> mymap; 
	mymap['a'] = 1; 
	mymap['b'] = 2; 
	mymap['c'] = 3; 

	// using begin() to print map 
	for (auto it = mymap.begin(); 
		it != mymap.end(); ++it) 
		cout << it->first << " = "
			<< it->second << '\n'; 
	return 0; 
} 

Output:

a = 1
b = 2
c = 3

map::end()

end() function is used to return an iterator pointing to the last element of the map container. end() function returns a bidirectional iterator to the last element of the container.   end返回指向map容器的最后一个元素的迭代器。

Syntax :

mapname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the last element.

Examples:

Input  : mymap['a'] = 1;
         mymap['b'] = 2;
         mymap['c'] = 3;
         mymap.end();
Output : returns an iterator to the element 'c' = 3

Input  : mymap['d'] = 1;
         mymap.end();
Output : returns an iterator to the element 'd' = 1

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.

// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <map> 
using namespace std; 

int main() 
{ 
	// declaration of map container 
	map<char, int> mymap; 
	mymap['a'] = 1; 
	mymap['b'] = 2; 
	mymap['c'] = 3; 

	// using begin() to print map 
	for (auto it = mymap.begin(); 
		it != mymap.end(); ++it) 
		cout << it->first << " = "
			<< it->second << '\n'; 
	return 0; 
} 

Output:

a = 1
b = 2
c = 3

map::size() in C++ STL


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 same key values.

map::size()
In C++, size() function is used to return the total number of elements present in the map.返回map中元素的个数

Syntax:

map_name.size()

Return Value: It returns the number of elements present in the map.

Examples:

Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
               }
        map1.size();
Output: 4

Input : map2 = {};
        map2.size();
Output: 0

// C++ program to illustrate 
// implementation of size() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Take any two maps 
	map<int, string> map1, map2; 
	
	// Inserting values 
	map1.insert(make_pair(1, "India")); 
	map1.insert(make_pair(2, "Nepal")); 
	map1.insert(make_pair(3, "Sri Lanka")); 
	map1.insert(make_pair(4, "Myanmar")); 
	
	// Printing the size 
	cout << "map1 size: " << map1.size(); 
	cout << endl; 
	cout << "map2 size: " << map2.size(); 
	return 0; 
} 

Output:

map1 size: 4
map2 size: 0

Time complexity: Constant i.e. O(1)

map::at() and map::swap() in C++ STL


Maps are the container in STL which is used to store the elements in the form of key-valuepair. Internally, the elements in a map are always sorted by its key. Maps are mainly implemented as binary search trees.

map::at()
at() function is used to return the reference to the element associated with the key k.返回key为k的元素

Syntax:

map1.at(k)

Parameters:
k is the Key value of the 
element whose associated value is accessed.

Return: It return a reference to the associated value of the element whose key value is equivalent to k.

Examples:

Input:  map1 = {
                 {1, 'a'},
                 {2, 'b'},
                 {3, 'c'},
                 {4, 'd'}
               }
        map1.at(2);
Output: b

Input:  map2 = {
                 {'w', 1},
                 {'x', 2},
                 {'y', 3}
               }
        map2.at('w');
Output: 1
// CPP program to illustrate 
// Implementation of swap() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Take any two maps 
	map<int, char> map1; 
	map<char, int> map2; 

	map1[1] = 'a'; 
	map1[2] = 'b'; 
	map1[3] = 'c'; 
	map1[4] = 'd'; 

	map2['w'] = 1; 
	map2['y'] = 2; 
	map2['z'] = 3; 

	// Print the associated element 
	cout << "Element at map1[2] = "
		<< map1.at(2) << endl; 

	cout << "Element at map2['w'] = "
		<< map2.at('w') << endl; 

	return 0; 
} 

Output:

Element at map1[2] = b
Element at map2['w'] = 1

map::swap()
swap() function is used to exchange the contents of two maps but the maps must be of same type, although sizes may differ.交换类型相同的两个map的元素,大小可以不同。
Syntax:

map1.swap(map2)
       OR
swap(map1, map2)

Parameters:
map1 is the first map object.
map2 is the second map object.

Return value: None

Examples:

Input : map1 = {
                 {1, 'a'},
                 {2, 'b'},
                 {3, 'c'},
                 {4, 'd'}
               }
        map2 = {
                 {5, 'w'},
                 {6, 'x'},
                 {7, 'y'}
               }
      swap(map1, map2)

Output : map1 = {
                 {5, 'w'},
                 {6, 'x'},
                 {7, 'y'}
                }
         map2 = {
                 {1, 'a'},
                 {2, 'b'},
                 {3, 'c'},
                 {4, 'd'}
                }
// CPP program to illustrate 
// Implementation of swap() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Take any two maps 
	map<int, char> map1, map2; 

	map1[1] = 'a'; 
	map1[2] = 'b'; 
	map1[3] = 'c'; 
	map1[4] = 'd'; 

	map2[5] = 'w'; 
	map2[6] = 'x'; 
	map2[7] = 'y'; 

	// Swap elements of queues 
	swap(map1, map2); 

	// Print the elements of maps 
	cout << "map1:\n"
		<< "\tKEY\tELEMENT\n"; 
	for (auto it = map1.begin(); 
		it != map1.end(); it++) 

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

	cout << "map2:\n"
		<< "\tKEY\tELEMENT\n"; 
	for (auto it = map2.begin(); 
		it != map2.end(); it++) 

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

	return 0; 
} 

Output:

map1:
    KEY    ELEMENT
    5    w
    6    x
    7    y
map2:
    KEY    ELEMENT
    1    a
    2    b
    3    c
    4    d

map erase() function in C++ STL

  1. map::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range.  删除特定key的元素。
  2. Syntax for erasing a key:
    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.
    Below program illustrate the above syntax:

// C++ program to illustrate 
// map::erase(key) 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 

	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 60 }); 
	mp.insert({ 5, 50 }); 

	// 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 
			<< '\t' << itr->second << '\n'; 
	} 

	// function to erase given keys 
	mp.erase(1); 
	mp.erase(2); 

	// 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 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

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
  1. Syntax for removing a position:
    map_name.erase(iterator position)
    

    Parameters: The function accept 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 returns anything.

    Below program illustrate the above syntax:

// C++ program to illustrate 
// map::erase(position) 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 
	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 60 }); 
	mp.insert({ 5, 50 }); 

	// 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 
			<< '\t' << itr->second << '\n'; 
	} 

	// function to erase given position 
	auto it = mp.find(2); 
	mp.erase(it); 

	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 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

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
  1. Syntax for erasing a given range:
    map_name.erase(iterator position1, iterator position2)
    

    Parameters: The function accepts two mandatory parameters which are described below:

    Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.

    Program below illustrate the above syntax:

    • 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 upto which removal is to be done.
// C++ program to illustrate 
// map::erase() 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

	// initialize container 
	map<int, int> mp; 
	// insert elements in random order 
	mp.insert({ 2, 30 }); 
	mp.insert({ 1, 40 }); 
	mp.insert({ 3, 60 }); 
	mp.insert({ 2, 20 }); 
	mp.insert({ 5, 50 }); 

	// 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 
			<< '\t' << itr->second << '\n'; 
	} 

	// 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 
			<< '\t' << itr->second << '\n'; 
	} 
	return 0; 
} 

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

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.删除所有元素,大小变为1.

Syntax:

map1.clear()
where map1 is the name of the map.

Parameters:
No parameters are passed.

Return Value: None

Examples:

Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
               }
        map1.clear();
Output: map1 = {}

Input : map2 = {}
        map2.clear();
Output: map2 = {}
// CPP program to illustrate 
// Implementation of clear() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// 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"; 
	cout << "map1 size = " << map1.size() << endl; 
	cout << "map2 size = " << map2.size() << endl;; 
	
	// Deleting the map elements 
	map1.clear(); 
	map2.clear(); 
	
	// Print the size of map 
	cout<< "Map size after running function: \n"; 
	cout << "map1 size = " << map1.size() << endl; 
	cout << "map2 size = " << map2.size(); 
	return 0; 
} 

Output:

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)

猜你喜欢

转载自blog.csdn.net/qq_27009517/article/details/86596846