0% found this document useful (0 votes)
12 views

C++ Map

Uploaded by

Rayen Bahri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C++ Map

Uploaded by

Rayen Bahri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

(https://srv.carbonads.net/ads/click/x/GTND427ECESIT2JWC674YKQUCT
ADS VIA CARBON
(HTTP://CARBONADS.NET/?UTM_SOURCE=WWWPROGRAMIZCOM&UTM_MEDIUM=AD_VIA_LINK&UTM_CAMPAIGN=IN_UNIT&UTM_TERM=CARBON)

C++ Map
In C++, maps are associative containers that store paired data. These paired
data are called key-value pairs, where the key is unique but the value is not.
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

A map named student

The elements in a map are internally sorted by their keys.

In order to use maps in C++, we must include the map header file in our program:

#include <map>
Create
Thank a Map
you for printing our content at www.domain-name.com. Please check back soon for new contents.

WeC++
can declare a PRO!
mapClaim
using the following (https://programiz.pro/learn/master-cpp?utm_source=sticky-
syntax:
36% off Try hands-on with Programiz Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials
std::map<key_type, & examples
value_type> map_name = {{key1, value1},{key2, value2}, ...};
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
Here,

std::map - declares an STL container of type map

<key_type> - the data type of the keys to be stored in the map

<value_type> - the data type of the values to be stored in the map

map_name - a unique name given to the map

key1, key2, ... - keys to be stored in the map

value1, value2, ... - values to be stored in the map

Let's see an example,

// create a map with integer keys and string values


std::map<int, string> student = {{1,"Jacqueline"}, {2,"Blake"}, {3,"Denise"}};

Note: We can also initialize map elements without using the assignment
operator = . For example,
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
std::map<int, string> student {{1,"Jacqueline"}, {2,"Blake"}, {3,"Denise"}

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

Map Methods
In C++, the map class provides various methods to perform different operations
on a map.

Operation Description

insert() adds an element (key-value pair) to the map

erase() removes an element or range of elements from the map

clear() removes all the elements from the map

find() searches the map for the given key

size() returns the number of elements in the map

empty() returns true if the map is empty


Add
Thank you Values in content
for printing our a Map at www.domain-name.com. Please check back soon for new contents.

WeC++
can use the []PRO!
operator to add (https://programiz.pro/learn/master-cpp?utm_source=sticky-
key-valuepairs to a map. For example,
36% off Try hands-on with Programiz Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
create Search
//(/)
PRO tutorials & examples
a floating&utm_campaign=programiz&utm_medium=referral)
map with integer keys and string values
std::map<int, string> student;
www.domain-name.com

// add element with key 1 and value "Jacqueline"


student[1] = "Jacqueline";

// add element with key 2 and value "Blake"


student[2] = "Blake";

We can also use the insert() function alongside the make_pair() function to
insert elements into the map. For example,

student.insert(std::make_pair(3, "Denise"));

We can generalize the above two methods into the following syntaxes:

// using the [] operator


map_name[key] = value;

// using the insert() and make_pair() functions


map_name.insert(std::make_pair(key, value));
Example
Thank 1: C++our
you for printing Maps
content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
#include <iostream> banner&utm_campaign=programiz&utm_medium=referral)
#include
Try <map>
Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
Search
PRO namespace tutorials & examples
using
(/) floating&utm_campaign=programiz&utm_medium=referral)
std;
www.domain-name.com
int main() {

map<int, string> student;

// use [] operator to add elements


student[1] = "Jacqueline";
student[2] = "Blake";

// use insert() method to add elements


student.insert(make_pair(3, "Denise"));
student.insert(make_pair(4, "Blake"));

// add elements with duplicate keys


student[5] = "Timothy";
student[5] = "Aaron";

for (int i = 1; i <= student.size(); ++i) {


cout << "Student[" << i << "]: " << student[i] << endl;
}

return 0;
}

Run Code (/cpp-programming/online-compiler)

Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
Student[1]: Jacqueline
Student[2]: Blake
(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-onStudent[3]: Denise
C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Student[4]: Blake
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
Student[5]: Aaron
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
In this program, we have created a map named student that stores int keys
and string values.

Notice that we have two duplicate values ( "Blake" ) in our program, which is
valid.

However, we also have two duplicate keys (5) in our program, which is invalid.

Here, since both "Timothy" and "Aaron" share the same key, only one of the
values is allowed to be stored.

First, "Timothy" is paired with the key 5 in student . Then, when "Aaron" is paired
with 5, "Timothy" is overwritten.

We then use a for loop to print all the map elements.

Note: When we use cout to print a map element directly, we only print the
corresponding map value, not its key.

// Output: Jacqueline
cout << student[1];
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

36% off Access Keys and Values


Try hands-on C++ with Programiz PRO! Claim Discount Now
(https://programiz.pro/learn/master-cpp?utm_source=sticky-
banner&utm_campaign=programiz&utm_medium=referral)
We
Trycan access
Programiz the keys and values of our map with the help of map iterators. For
(https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
example,
www.domain-name.com

#include <iostream>
#include <map>
using namespace std;

int main() {

map<int, string> student;

student[1] = "Jacqueline";
student[2] = "Blake";
student[3] = "Denise";
student[4] = "Aaron";

// declare map iterator


map<int, string>::iterator iter;

// use iterator to display map elements


for (iter = student.begin(); iter != student.end(); ++iter) {
cout << iter->first << " - " << iter->second << endl;
}

return 0;
}

Run Code (/cpp-programming/online-compiler)


Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on1C++
- with Programiz PRO! Claim Discount Now
Jacqueline banner&utm_campaign=programiz&utm_medium=referral)
2 - Blake
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
3 - DeniseSearch tutorials & examples
PRO floating&utm_campaign=programiz&utm_medium=referral)
4 (/)
- Aaron
www.domain-name.com

In the above example, we have used a custom iterator iter to access the keys
and values of the student map. The key is given by the first object, and the
value by the second object.

Notice that we have used a for loop with the iter iterator to display all the
elements of student .

for (iter = student.begin(); iter != student.end(); ++iter) {


cout << iter->first << " - " << iter->second << endl;
}
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
Here, banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
begin()
PRO Search tutorials & examples
- floating&utm_campaign=programiz&utm_medium=referral)
returns an iterator that points to the first element of the map
(/)
www.domain-name.com
end() - returns an iterator that points to the theoretical element following the
last element of the map.

We have used the -> operator with iter to access the first and second

objects.

Alternatively, we can also dereference iter and use the . operator to access
first and second .

// Output: 1
cout << (*iter).first << " - ";

// Output: Jacqueline
cout << (*iter).second;

C++ find() Function for Maps


We can search for keys in a map using the find() function. Its syntax is

map_name.find(key);
Foryou
Thank example,
for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-onmap<int,
C++ with Programiz
string>PRO! Claim Discount Now
student; banner&utm_campaign=programiz&utm_medium=referral)
map<int, string>::iterator iter;
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
student[1] = "Jacqueline";
student[2] = "Blake"; www.domain-name.com

// find the key 2 in the student map


// store the return value in iter
iter = student.find(2);

In the example above, we have used the find() function to search for the
element of student that contains the key 2.

Now, the find() function returns:

an iterator pointing to the element if the element exists

an iterator pointing to the end of the map i.e. student.end() if the element
doesn't exist.

Delete Elements from C++ Maps


We can delete map elements with the erase() and clear() functions.

Let's talk about the clear() function first.


C++
Thank clear()
you Function
for printing foratMaps
our content www.domain-name.com. Please check back soon for new contents.

The clear() function deletes all the elements(https://programiz.pro/learn/master-cpp?utm_source=sticky-


of the map. For example,
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
map<int, string> student;& examples
Search tutorials
PRO
(/) floating&utm_campaign=programiz&utm_medium=referral)
student[1] = "Jacqueline";
student[2] = "Blake"; www.domain-name.com

cout << student.size(); // Output: 2

student.clear();

cout << student.size(); // Output: 0

C++ erase() Function for Maps

We can use the erase() function to delete individual elements either with the
help of iterators or with keys.

Suppose we have a map named student_rank as follows:

map <string, int> student_rank {{"Josh", 2}, {"Rachel", 4}, {"Betty", 6}};

Now, we can delete elements of this map in the following ways:

1. erase() Using a Key


Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
// delete element with key "Rachel" from the map
student_rank.erase("Rachel");
(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
2.Try
erase() (https://programiz.pro/learn/master-cpp?utm_source=nav-
Using
Programiz an Iterator
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
// initialize an iterator pointing to the beginning of the map
map <string, int>::iterator itr = student_rank.begin();

// increment the iterator to point to the second element


itr++;

// delete the second element


student_rank.erase(itr);
Example
Thank 2: erase()
you for printing to Remove
our content Individual Elements
at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
#include <iostream> banner&utm_campaign=programiz&utm_medium=referral)
#include
Try <map>
Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
using
PRO Search
namespace tutorials & examples
std;
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
int main() {

// create a map named student


map <int, string> student {{1, "Denise"}, {2, "Blake"}, {3, "Courtney"}, {4

// create map iterator


map <int, string>::iterator itr;

// display initial map values


cout << "Initial Values:" << endl;

for(itr = student.begin(); itr != student.end(); ++itr) {


cout << itr->second << ", ";
}

cout << endl;

// use itr iterator to point to the first map element


itr = student.begin();

// remove the first element


student.erase(itr);

// remove the element having key 4

Run Code (/cpp-programming/online-compiler)

Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.
Initial Values:
Denise, Blake, Courtney, John, Jennifer,
(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Final Values:
Blake,
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
Courtney, Jennifer,
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
In the above program, we have used the erase() function to delete individual
map elements.

First, we deleted the first map element by supplying the itr iterator to erase() .

itr = student.begin();
student.erase(itr);

Note: We have also used the itr iterator to loop through the map.

Then, we deleted the map element possessing the key 4 by supplying the key to
erase() .

student.erase(4);
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

Remove Individual Map Elements

Delete a Range of Elements

The erase() function can also be used to remove a range of elements from the
map. For this, we need to pass two iterators to the erase() function:

my_map.erase(itr_first, itr_last);

Here,

itr_first - iterator to the first element to remove

itr_last - iterator to the element succeeding the last element to remove

Here, itr_first is inclusive, meaning it is removed, while itr_last is not


inclusive, meaning it is not removed. Obviously, all the elements in between are
removed as well.

Note that the elements in a map are internally sorted by their key.
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

36% off
Example 3: erase() to Remove a Range of(https://programiz.pro/learn/master-cpp?utm_source=sticky-
Elements
Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
#include
PRO Search tutorials & examples
<iostream>
(/) floating&utm_campaign=programiz&utm_medium=referral)
#include <map>
www.domain-name.com
using namespace std;

int main() {

// create a map named student


map <int, string> student {{1, "Denise"}, {2, "Blake"}, {3, "Courtney"}, {4

// create a map iterator


map <int, string>::iterator iter;

// display initial map values


cout << "Initial Values:" << endl;
for(iter = student.begin(); iter != student.end(); ++iter) {
cout << iter->second << ", ";
}

cout << endl;

// remove a range of elements


student.erase(student.find(2),student.find(5));

// display final map values


cout << "\nFinal Values:" << endl;

for(iter = student.begin(); iter != student.end(); ++iter) {


cout << iter->second << ", ";

Run Code (/cpp-programming/online-compiler)


Output
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents.

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-onInitial
C++ with Programiz
Values: PRO! Claim Discount Now banner&utm_campaign=programiz&utm_medium=referral)
Denise, Blake, Courtney, John, Jennifer,
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
Final Values:
Denise, Jennifer, www.domain-name.com

In the above program, we have removed the map elements between the keys 2
and 5.

However, notice that the element with the key 5 is not removed, while the element
with the key 2 is removed.

This is because erase() removes the starting element of the given range but
doesn't remove the end element.

Remove a Range of Map Elements

Share on:
(https://www.facebook.com/sharer/sharer.php?
Thank you for printing our content at www.domain-name.com. Please(https://twitter.com/intent/tweet?
check back soon for new contents.
u=https://www.programiz.com/cpp- text=Check%20this%20amazing%20article%20on%
programming/map) programming/map)
(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-on C++ with Programiz PRO! Claim Discount Now
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
DidPRO Search
you find this tutorials
article helpful?& examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com

Related Tutorials
ThankC++
you for printing our content at www.domain-name.com.
Tutorial Please check back soon for new contents.
C++ Tutorial

(https://programiz.pro/learn/master-cpp?utm_source=sticky-
36% off Try hands-onC++
C++ Multimap
with Programiz PRO! Claim Discount Now C++ Unordered Map
banner&utm_campaign=programiz&utm_medium=referral)
Try Programiz (https://programiz.pro/learn/master-cpp?utm_source=nav-
PRO Search tutorials & examples
(/) floating&utm_campaign=programiz&utm_medium=referral)
www.domain-name.com
(/cpp-programming/multimap) (/cpp-programming/unordered-map)

C++ Tutorial C++ Tutorial

C++ Vectors How to pass and return object from


C++ Functions?

(/cpp-programming/vectors) (/cpp-programming/pass-return-object-
function)

You might also like