Map in C++ Standard Template Library (STL) - GeeksforGeeks (2024)

Last Updated : 05 Jul, 2024

Improve

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.

std::map is the class template for map containers and it is defined inside the <map> header file.

Basic std::map Member Functions

Some basic functions associated with std::map are:

  • begin() – Returns an iterator to the first element in the map.
  • end() – Returns an iterator to the theoretical element that follows the 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.

Examples of std::map

The following examples shows how to perform basic operations on map containers.

Example 1: begin() and end() Function

C++
// C++ program to illustrate the begin and end iterator#include <iostream>#include <map>#include <string>using namespace std;int main(){ // Create a map of strings to integers map<string, int> mp; // Insert some values into the map mp["one"] = 1; mp["two"] = 2; mp["three"] = 3; // Get an iterator pointing to the first element in the // map map<string, int>::iterator it = mp.begin(); // Iterate through the map and print the elements while (it != mp.end()) { cout << "Key: " << it->first << ", Value: " << it->second << endl; ++it; } return 0;}

Output

Key: one, Value: 1Key: three, Value: 3Key: two, Value: 2

Complexity of the above method:

Time complexity: O(n) where n is the size of map.

Auxiliary Space: O(n)

Example 2: size() function

C++
// C++ program to illustrate the size() function#include <iostream>#include <map>#include <string>using namespace std;int main(){ // Create a map of strings to integers map<string, int> map; // Insert some values into the map map["one"] = 1; map["two"] = 2; map["three"] = 3; // Print the size of the map cout << "Size of map: " << map.size() << endl; return 0;}

Output

Size of map: 3

Complexity of the above method:

Time complexity: O(1).

Example 3: Implementing Map

CPP
// CPP Program to demonstrate the implementation in Map// divyansh mishra --> divyanshmishra101010#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)); // another way of inserting a value in a map gquiz1[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 10The map gquiz2 after assign from gquiz1 is : KEY ELEMENT 1 40 2 30 3 60 4 20 5 50 6 50 7 10gquiz2 after remov...

Complexity of the above method:

Time complexity: O(n log(n)) as n is size of the map
Auxiliary space: O(n)

Example 4: Implementing Map of Integers

C++
// C++ program to implement map container#include <iostream>#include <map>#include <string>using namespace std;int main(){ // Create a map of strings to integers map<string, int> map; // Insert some values into the map map["one"] = 1; map["two"] = 2; map["three"] = 3; // Print the values in the map cout << "Key: one, Value: " << map["one"] << endl; cout << "Key: two, Value: " << map["two"] << endl; cout << "Key: three, Value: " << map["three"] << endl; // Check if a key is in the map if (map.count("four") > 0) { cout << "Key 'four' is in the map" << endl; } else { cout << "Key 'four' is not in the map" << endl; } return 0;}

Output

Key: one, Value: 1Key: two, Value: 2Key: three, Value: 3Key 'four' is not in the map

List of all Functions of std::map

The following table contains all the functions defined inside std::map class.

Function

Definition

map::insert()

Insert elements with a particular key in the map container –> O(log n)

map:: count()

Returns the number of matches to element with key-value ‘g’ in the map. –> O(log n)

map equal_range()

Returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k.

map erase()

Used to erase elements from the container –> O(log n)

map rend()

Returns a reverse iterator pointing to the theoretical element right before the first key-value pair in the map(which is considered its reverse end).

map rbegin()

Returns a reverse iterator which points to the last element of the map.

map find()

Returns an iterator to the element with key-value ‘g’ in the map if found, else returns the iterator to end.

map crbegin() and crend()

crbegin() returns a constant reverse iterator referring to the last element in the map container. crend() returns a constant reverse iterator pointing to the theoretical element before the first element in the map.

map cbegin() and cend()

cbegin() returns a constant iterator referring to the first element in the map container. cend() returns a constant iterator pointing to the theoretical element that follows the last element in the multimap.

map emplace()

Inserts the key and its element in the map container.

map max_size()

Returns the maximum number of elements a map container can hold –> O(1)

map upper_bound()

Returns an iterator to the first element that is equivalent to mapped value with key-value ‘g’ or definitely will go after the element with key-value ‘g’ in the map

map operator=

Assigns contents of a container to a different container, replacing its current content.

map lower_bound()

Returns an iterator to the first element that is equivalent to the mapped value with key-value ‘g’ or definitely will not go before the element with key-value ‘g’ in the map –> O(log n)

map emplace_hint()

Inserts the key and its element in the map container with a given hint.

map value_comp()

Returns the object that determines how the elements in the map are ordered (‘<‘ by default).

map key_comp()

Returns the object that determines how the elements in the map are ordered (‘<‘ by default).

map::size()

Returns the number of elements in the map.

map::empty()

Returns whether the map is empty

map::begin() and end()

begin() returns an iterator to the first element in the map. end() returns an iterator to the theoretical element that follows the last element in the map

map::operator[]

This operator is used to reference the element present at the position given inside the operator.

map::clear()

Removes all the elements from the map.

map::at() and map::swap()

at() function is used to return the reference to the element associated with the key k. swap() function is used to exchange the contents of two maps but the maps must be of the same type, although sizes may differ.



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } document.getElementById('article-video-tab-content').style.display = 'block'; } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); // error handling for no compatible source player.on('error', function() { var error = player.error(); console.log("Video Error: ", error); if (error && error.code === 4) { console.log("No compatible source was found for this media."); hideVideoPlayer(); } }); }, function(err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); hideVideoPlayer(); // hiding video in case of timeout (requirejs) console.log(err); }); // function to hide the video player function hideVideoPlayer() { var videoPlayer = document.getElementById('article-video'); if (videoPlayer) { videoPlayer.parentNode.removeChild(videoPlayer); } } /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content // element = document.getElementById('article-video-tab-content'); // element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Map in C++ Standard Template Library (STL) - GeeksforGeeks (2024)
Top Articles
Dit zijn de vijf domste beginnersfouten die ik maakte in Baldur's Gate 3
Baldur’s Gate 3: essentiële beginnerstips
LAC-318900 - Wildfire and Smoke Map
El Paso Craigs
Hsqa Online Renewal System
Spectrum Store Appointment
Pobierz Papa's Mocharia To Go! na PC za pomocą MEmu
Craigslist In Lakeland
Trey Yingst Parents Nationality
9:00 A.m. Cdt
Lowes Maytag Pet Pro Commercial Actress
What Does Purge Mods Do In Vortex
The Dillards: From Mayberry's Darlings to Progressive Bluegrass Pioneers
5 high school boys cross country stars of the week: Sept. 13 edition
Free Cities Mopoga
Pear Shaped Rocsi
Pain Out Maxx Kratom
Math Nation Algebra 2 Practice Book Answer Key
Eurail Pass Review: Is It Worth the Price?
Guide:How to make WvW Legendary Armor
Ayala Rv Storage
Seconds Valuable Fun Welcoming Gang Back Andy Griffith's Birthday A Top Wish So A Happy Birthday FZSW A Fabulous Man Kevin Talks About Times From Ten Day Weekend Fun Labor Day Break
27 Sage Street Holmdel Nj
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Craigslist Mexico Cancun
Police in Germany arrest 25 people allegedly planning to overthrow the government
Sam's Club Stafford Gas Price
Age Of Attila's Rain Crossword
Jasminx Fansly
Kirby D. Anthoney Now
Philasd Zimbra
Kate Spade Outlet Altoona
7066642123
Charter Spectrum Appointment
Enterprise Car Sales Jacksonville Used Cars
Matrizen | Maths2Mind
Melissa Black County Court Judge Group 14
How to Get Rid of Phlegm, Effective Tips and Home Remedies
Opsb Pay Dates
Bad Moms 123Movies
Alylynn
Used Go Karts For Sale Near Me Craigslist
Waffle House Gift Card Cvs
Limestone Bank Hillview
Pulp Fiction 123Movies
Busted Newspaper Mcpherson Kansas
Priscilla 2023 Showtimes Near Regal Escondido
Cetaphil Samples For Providers
Nike.kronos/Wfm/Login
Function Calculator - eMathHelp
Ark Extinction Element Vein
Evalue Mizzou
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 6279

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.