The Wayback Machine - https://web.archive.org/web/20241127235814/https://www.geeksforgeeks.org/map-associative-containers-the-c-standard-template-library-stl/
Open In App

Map in C++ Standard Template Library (STL)

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 1
Key: three, Value: 3
Key: two, Value: 2

Complexity of the above method:

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

Auxiliary Space: O(n)

For a deeper understanding of maps and other associative containers in STL, our Complete C++ Course offers comprehensive lessons on how to use maps and improve your efficiency in problem-solving.

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    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

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: 1
Key: two, Value: 2
Key: three, Value: 3
Key 'four' is not in the map

Example 5: Implement map and assign value in one line

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
    // and inserting values
    map<string, int> map = {{"one", 1},
    {"two", 2}, {"three", 3}};

    // Print the values in the map

    for (auto a : map) {
        cout << "Key: " << a.first <<
        ", values: " << a.second << endl;
    }


    return 0;
}

Output
Key: one, values: 1
Key: three, values: 3
Key: two, values: 2

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.




Similar Reads

Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --> O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the <set> header file. Syntax: std:
7 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its eleme
4 min read
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in <utility> header consisting of two data elements or objects. The first element is referen
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward_list. std::
6 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash
6 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 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 the key k. Syntax: map1.at(k) Parameters: k is the
3 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
<iterator> library in C++ STL
Iterators in C++ STL | Introduction Functions Iterator operations : std :: advance : Advance iteratorstd :: distance : Return distance between iteratorsstd :: begin : Iterator to beginningstd :: end : Iterator to endstd :: prev : Get iterator to previous elementstd :: next : Get iterator to next elementstd :: next vs std :: advanceAll functions in
1 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
Searching in a Map Using std::map Functions in C++
In C++, map container is defined as std::map class template that also contains member function to search for an element on the bases of the keys. In this article, we will learn different methods to search for an element with the given key in C++. The recommended method to search for the given key in a map container is by using map find() function.
4 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 parameters are passed. Returns : True, if map is empty
1 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 at() function, the only difference is that the at(
2 min read
Default values in a Map in C++ STL
Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map<int,int> mpp; mpp[1]; ) if the key is
2 min read
set vs map in C++ STL
set and map in STL are similar in the sense that they both use Red Black Tree (A self balancing BST). Note that the time complexities of search, insert and delete are O(Log n). Differences: The difference is set is used to store only keys while map is used to store key value pairs. For example consider in the problem of printing sorted distinct ele
4 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 multiple keys of the same value. Syntax: map_name.emplac
2 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. Syntax: map_name.cbegin()Parameters: The function d
3 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 criterion. Syntax: map_name.crbegin()Parameters: The f
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 hold. C/C++ Code // C++ program to illustrate // map
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 as key and element=0. Syntax: map_name.upper_boun
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 of map1. Return Value: This function does not retur
2 min read
Practice Tags :
three90RightbarBannerImg