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:
map rend() function in C++ STL
Next article icon

map::operator[] in C++ STL

Last Updated : 09 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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::operator[]


This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator inserts a new element with that key and returns a reference to its mapped value, increasing the container size by one, the element is constructed using its default constructor if no value is provided.
Syntax : 
 

mapname[key] Parameters : Key value mapped to the element to be fetched. Returns : Direct reference to the element at the given key value.


Examples: 
 

Input  :  map mymap;           mymap['a'] = 1;           mymap['a']; Output :  1  Input  :  map mymap;           mymap["abcd"] = 7;           mymap["abcd"]; Output :  7 
CPP
// CPP program to illustrate // Implementation of [] operator #include <iostream> #include <map> #include <string> using namespace std;  int main() {     // map declaration     map<int, string> mymap;      // mapping integers to strings     mymap[1] = "Hi";     mymap[2] = "This";     mymap[3] = "is";     mymap[4] = "GeeksForGeeks";      // using operator[] to print string     // mapped to integer 4     cout << "mymap[4] is " << mymap[4] << '\n';     // using operator[] to access the key is not in the map     // it displays the default value in the constructor     cout << "mymap[5] is " << mymap[5] << '\n';     // the map size increases to 5     cout << "mymap now contains " << mymap.size()          << " elements.\n";      return 0; } 

Output
mymap[4] is GeeksForGeeks mymap[5] is  mymap now contains 5 elements. 


Time Complexity: O(logn)
 


Next Article
map rend() function in C++ STL

A

AyushSaxena
Improve
Article Tags :
  • Misc
  • C++
  • STL
  • cpp-map
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

    Map in C++ STL
    In C++, maps are associative containers that store data in the form of key value pairs sorted on the basis of keys. No two mapped values can have the same keys. By default, it stores data in ascending order of the keys, but this can be changes as per requirement.Example:C++#include <bits/stdc++.h
    8 min read
    Different Ways to Initialize a Map in C++
    Initializing map refers to the process of assigning the initial values to the elements of map container. In this article, we will learn different methods to initialize the map in C++. Let's start from the easiest method:Using Initializer ListThe simplest way to initialize an std::map container is by
    3 min read
    Inserting Elements in a Map in C++
    In C++, map stores unique key value pairs in sorted order and provides fast insert, delete and search operation. In this article, we will learn different methods to insert an element in a map in C++.The recommended method to insert an element in a map is by using map insert() method. Let’s take a lo
    4 min read
    Different ways to delete elements in std::map (erase() and clear())
    This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() 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
    4 min read

    Commonly Used Methods

    map::begin() and end() in C++ STL
    The std::map::begin() and std::map::end() are built-in functions used to retrieve iterators to the beginning and the end of a std::map container. Both functions are member functions of the std::map class defined inside the <map> header file.Example:C++// C++ Program to illustrate the use of //
    4 min read
    map::size() in C++ STL
    In C++, the std::map::size() is a built-in method used to find the number of elements in std::map container. It is the member function of std::map defined inside <map> header fie. In this article, we will learn about std::map::size() method in C++.Example:C++// C++ Program to illustrate the us
    2 min read
    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 param
    2 min read
    map insert() in C++ STL
    The std::map::insert() is a built-in function of C++ STL map container which is used to insert new elements into the map. In this article, we will learn how to use map::insert() function in our C++ programs.Example:C++// C++ program to illustrate how to use // map::insert #include <bits/stdc++.h
    5 min read
    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 multip
    2 min read
    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-value pair. 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
    3 min read
    map find() function in C++ STL
    The std::map::find() is a built-in function in C++ STL that is used to find an element with given key in the map. It is a member function of std::map container so we can directly use it with any map.Syntaxmap_name.find(key)Parameterskey: Key of the pair to be searched in the map container.Return Val
    2 min read
    map count() Function in C++ STL
    The std::map::count() in C++ is a built-in function that is used to count the occurrence of the given key in the map container. It is the member function of the std::map container.In this article, we will learn how to use std::map::count() in C++.Syntaxmp.count(key)Parameters key: The value whose oc
    2 min read
    map erase() Function in C++ STL
    In C++, std::map::erase() is a built-in function of std::map container that is used to remove elements from the map using their key or iterator. We can also remove multiple elements using iterators. In this article, we will learn how to use the map::erase() in C++SyntaxThe std::string::erase() funct
    3 min read
    map clear() in C++ STL
    The map clear() function in C++ is used to remove all elements from the map container and make its size to 0. In this article, we will learn about the map clear() function in C++.Let’s take a quick look at a simple example that uses map clear() method:C++#include <bits/stdc++.h> using namespac
    2 min read
    map::operator[] 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::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the
    2 min read

    Other Member Methods

    map rend() function in C++ STL
    The rend() function is an inbuilt function in C++ STL which 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). Syntax: map_name.rend() Parameters:The function does not take any parameter. Return Value:
    2 min read
    map crbegin() and crend() function in C++ STL
    map::crbegin() is a built-in function in C++ STL that returns a constant reverse iterator referring to the last element in the map container. Since map container contains the element in an ordered way, crbegin() will point to that element that will come last according to the container's sorting crit
    3 min read
    map cbegin() and cend() function in C++ STL
    map::cbegin() is a built-in function in C++ STL that returns a constant iterator referring to the first element in the map container. Since map container contains the element in an ordered way, cbegin() will point to that element that will come first according to the container's sorting criterion. S
    3 min read
    map max_size() in C++ STL
    The map::max_size() is a built-in function in C++ STL which returns the maximum number of elements a map container can hold. Syntax: map_name.max_size() Parameters: This function does not accept any parameters. Return Value: This function returns the maximum number of elements a map container can ho
    1 min read
    map upper_bound() function in C++ STL
    The map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container
    2 min read
    map operator= in C++ STL
    The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content. Syntax: map1_name = map2_name Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements o
    2 min read
    map::lower_bound() in C++ STL
    In C++, std::map::lower_bound() is a built-in method used to find the first element in the map whose key is either equal to or greater than the given key. In this article, we will learn about std::map::lower_bound() function in C++.Example:C++// C++ Program to illustrate the use of // std::map::lowe
    4 min read
    map emplace_hint() function in C++ STL
    The map::emplace_hint() is a built-in function in C++ STL which inserts the key and its element in the map container with a given hint. It effectively increases the container size by one as map is the container that stores keys with the element value. The hint provided does not affect the position t
    2 min read
    map value_comp() in C++ STL
    The std::map::value_comp() is a function in C++ STL. It returns a function object that compares objects of type std::map::value. Syntax: value_compare value_comp() const Parameters: It does not accept any parameters. Returns: This method returns a function object that compares objects of type std::m
    2 min read
    map key_comp() function in C++ STL
    The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys. Syntax: map.key_comp() Return value: This method returns the comparison object used by container that compare keys. Below examples illustrate the working of key_comp() method
    2 min read
    map equal_range() in C++ STL
    The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pai
    2 min read
    Map and External Sorting Criteria/Comparator in C++ STL
    C++ Map is another commonly used STL container, it stores elements in a mapped fashion. Each element is stored as a pair having a key value and a mapped value. No two mapped values can have the same key values which means each key is unique. By default, key values in the map are in lexicographically
    4 min read
    Get Map Element at Offset in C++ STL
    Prerequisites: Map in C++ STL Since the map is not indexed as arrays or vectors sequential access is not possible in the map but to access an element at a particular offset. Example: inserted elements are { 'a',11 } , { 'b',12 } , { ' c ', 13 } then we can get { 'b', 12 } for 2 position. Methods to
    3 min read
    Search by value in a Map in C++
    Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the given value K. If there is no key value mapped to K then print "-1".Examples: Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 Output: 1 2 10 Explanation: The 3
    2 min read
    Passing Map as Reference in C++ STL
    Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms
    3 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