Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
How to Access a Value in a Map Using a Key in C++?
Next article icon

How to Access a Value in a Map Using a Key in C++?

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, std::map container store data in the form of key-value pairs where keys are associated with the given value. In this article, we will learn how to access a value in a std::map using key in C++.

Examples

Input: m = {{'a', 11}, {'b', 45}, {'c', 9}}, k = 'c'
Output: 9
Explanation: The key 'c' present in the map with value 9.

Input: m = {{'a', 11}, {'b', 45}, {'c', 9}}, k = 'a'
Output: 11
Explanation: The key a present in the map with value 11.

Following are the 3 different methods to access the value of key in std::map in C++:

Table of Content

  • Using Operator []
  • Using map::at() Method
  • Using map::find() Method

Using Operator []

The simplest way is to use the [] operator to access the value associated with a key. We pass the key inside the [] brackets and it returns the associated value.

Example

C++
// C++ Program to access the value in a map // using a key with [] operator #include <bits/stdc++.h> using namespace std;  int main() {     map<char, int> m = {{'a', 11}, {'b', 45},                          {'c', 9}};     char k = 'c';      // Accessing the value of key in std::map     // using [] operator     cout << m[k];     return 0; } 

Output
9

Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)

Note: If the key doesn't exists in the map, then instead of returning an error, this operator will create a new element with the given key and default initialized value.

Using map::at() Method

The std::map::at() method provides a safer method to access to the value associated with a given key in std::map. Unlike [] operator, if the key does not exist, it throws an std::out_of_range exception.

Syntax

m.at(k);

where m is the map and k is the key to be searched.

Example

C++
// C++ Program to illustrate how to access // a value in std::map using a key with // std::map::at() method #include <bits/stdc++.h> using namespace std;  int main() {     map<char, int> m = {{'a', 11}, {'b', 45},                          {'c', 9}, {'d', 21}}; 	char k = 'c';      // Accessing the value of key in std::map     // using std::map::at()     cout << m.at(k);     return 0; } 

Output
9

Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)

Using map::find() Method

We can also access the value of key in std::map using std::map::find() method. This function will return an iterator to the key-value pair if the key present, else returns an iterator pointing to the std::map::end().

Syntax

m.find(k);

where m is the map and k is the key to be searched.

Example

C++
// C++ Program to illustrate how to access // a value in a map using a key with // std::map::find() method #include <bits/stdc++.h> using namespace std;  int main() {     map<char, int> m = {{'a', 11}, {'b', 45},                          {'c', 9}};     char k = 'c';     // Finding the key in std::map     auto it = m.find(k);      // Checking if the key is found     if (it != m.end())         cout << it->second;     else         cout << "Key " << k << " is NOT Present";     return 0; } 

Output
9

Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)


Next Article
How to Access a Value in a Map Using a Key in C++?

N

nikitamehrotra99
Improve
Article Tags :
  • C++ Programs
  • C++
  • STL
  • cpp-map
  • CPP Examples
Practice Tags :
  • CPP
  • STL

Similar Reads

    How to Access Value in a Map Using Iterator in C++?
    In C++, a map is a container that stores elements in the form of a key value and a mapped value pair. In this article, we will learn how to access a value in a map using an iterator in C++. Accessing Value in a Map Using Iterator in C++To access a value associated with a key in a std::map using an i
    2 min read
    How to Update Value of a Key in Map in C++?
    In C++, a map is a data structure that stores key-value pairs. In this article, we will learn how to change the value of a key that is already present in the map container in C++. Example Input: map<int, string> mp = {(1, "One"), (2,"Two")} Output: map after Updation: {(1, "One"), (2, "Three")
    2 min read
    How to Replace a Key-Value Pair in a Map in C++?
    A map in C++ is a part of the Standard Template Library (STL) that allows the user to store data in key-value pairs where each key in a map must be unique. In this article, we will learn how to replace a specific key-value pair in a Map in C++. Example: Input : map<int, string> mp={{1,"John"},
    2 min read
    How to Find First Key-Value Pair in a Map in C++?
    In C++ STL, a map is a container that stores key-value pairs in an ordered or sorted manner. In this article, we will learn how to find the first key-value pair in a Map. Example: Input: myMap = {{1, "C++"}, {2, "Java"}, {3, "Python"}, {4, "JavaScript"}}; Output: First key-Value Pair : (1, C++)Getti
    2 min read
    How to Delete a Key-Value Pair from a Map in C++?
    In C++, maps are used to store key-value pairs in which each key is unique. In this article, we will learn how to delete a key-value pair from a map in C++. Example Input: mp={ {1,"One"}, {2,"Two"},{3,"Three"}}Key= 2Output: Map after deleting key: 1: One3: ThreeRemove a Key-Value Pair from Map in C+
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences