map insert() in C++ STL Last Updated : 11 Jan, 2025 Comments Improve Suggest changes Like Article Like Report 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> using namespace std; int main() { map<int, string> m; // Insert single elements in random order m.insert({1, "one"}); // Insert multiple elements m.insert({{2, "two"}, {4, "four"}}); for (auto i : m) cout << i.first << ": " << i.second << '\n'; return 0; } Output1: one 2: two 4: four SyntaxThe map::insert() function provides 4 different overloads:m.insert({k, v}) // For single elementm.insert(pos, {k, v}) // For single element near posm.insert({ {k1, v1}, {k2, v2}, ....}); // For multiple elementsm.insert(first, last); // For rangeWe can use these overloads for different ways to insert elements in std::map() in C++:Table of ContentInsert Single ElementInsert Element Near the Given PositionInserting Multiple ElementsInserting Elements from Given RangeInsert Single ElementWe can use the map::insert() to insert a key value pair in the map. It will be inserted at the position according to the order of the map elements.Syntaxm.insert({k, v})Parameters{k, v}: Key-value pair to be inserted.Return ValueReturns a pair, where pair::first is an iterator pointing to either the newly inserted element or to the element with same key in the map.The pair::second is a boolean value that tells whether the insertion was successful or not.Note: As map contains only unique key value pairs, map::insert() function won't insert the elements that is already present in the map.The insert() function is essential for adding elements to a map. Example C++ // C++ program to illustrate how to use // map::insert to insert a single element #include <bits/stdc++.h> using namespace std; int main() { map<int, string> m; // Insert single elements in random order m.insert({1, "one"}); m.insert({4, "four"}); m.insert({2, "two"}); // Trying to insert duplicate key m.insert({2, "TWO"}); for (auto i : m) cout << i.first << ": " << i.second << '\n'; return 0; } Output1: one 2: two 4: four Time Complexity: O(log n), where n is the number of elements.Auxiliary Space: O(1)Insert Element Near the Given PositionWe can also use the map::insert() function to insert the key-value pair near the given position. std::map has to maintain the order of elements. We cannot force the insertion at any particular position, so the given position only gives a hint to the map::insert() function as from where to start searching for the place to insert.Syntaxm.insert(pos, {k, v})Parameters{k, v}: Key-value pair to be inserted.pos: Iterator to the position near which the new element is to be inserted.Return ValueReturns an iterator pointing to either the newly inserted element or to the element with same key in the map.Example: Inserting an Element Near Given Position C++ // C++ program to illustrate how to use // map::insert to insert the given pair // near some specific position #include <bits/stdc++.h> using namespace std; int main() { map<int, string> m; m.insert({1, "one"}); m.insert({4, "four"}); // Finding the position to insert auto i = m.find(4); // Inserting {3, 60} starting the search // from position where 2 is present m.insert(i, {2, "two"}); for (auto i : m) cout << i.first << ": " << i.second << '\n'; return 0; } Output1: one 2: two 4: four Time Complexity: O(log n)Auxiliary Space: O(1)Insert Multiple ElementsWe can insert multiple key value pairs in a map using map::insert() by enclosing the multiple key value pairs inside the braces {} and separate each of them using a comma. This form is called initializer list.Syntaxm.insert({ {k1, v1}, {k2, v2}, ....});Parameters{k1, v1}, {k2, v2}...: First pair, second pair and so on inside { } braces.Return ValueThis function does not return anything.Example C++ // C++ program to illustrate how to use // map::insert to insert multiple key-value // pairs using initializer list #include <bits/stdc++.h> using namespace std; int main() { map<int, string> m; // Insert multiple key-value pairs using // initializer list m.insert({{1, "one"}, {2, "two"}, {4, "four"}}); // Display the elements of the map for (auto i : m) cout << i.first << ": " << i.second << '\n'; return 0; } Output1: one 2: two 4: four Time Complexity: O(k log n), where n is the number of elements already present in the map.Auxiliary Space: O(k), where k is the number of elements to be inserted.Insert Elements from Given RangeThe map::insert() function can also be used to insert elements from the given range. This range can by any STL container or an array.Syntaxm.insert(first, last);Parametersfirst: Iterator to the first of the range.last: Iterator to the element just after the last element of the range.Return ValueThis function does not return anything.Example C++ // C++ program to illustrate how to use // map::insert to insert multiple elements // from a given range of an STL container #include <bits/stdc++.h> using namespace std; int main() { map<int, string> m; // Vector of pairs to insert into the map vector<pair<int, string>> v = {{1, "one"}, {2, "two"}, {4, "four"}}; // Insert elements from vector m.insert(v.begin(), v.end()); for (auto i : m) cout << i.first << ": " << i.second << '\n'; return 0; } Output1: one 2: two 4: four Time Complexity: O(k log n), where n is the number of elements in the map.Auxiliary Space: O(k), where k is the number of elements in the range. Comment More infoAdvertise with us Next Article map emplace() in C++ STL gopaldave Follow Improve Article Tags : Misc C++ STL CPP-Functions cpp-containers-library cpp-map cpp-map-functions +3 More Practice Tags : CPPMiscSTL 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 Methodsmap::begin() and end() in C++ STLThe 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++ STLIn 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++ STLMaps 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++ STLThe 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++ STLThe 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++ STLMaps 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++ STLThe 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++ STLThe 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++ STLIn 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++ STLThe 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++ STLMaps 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 Methodsmap rend() function in C++ STLThe 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++ STLmap::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++ STLmap::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++ STLThe 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++ STLThe 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++ STLThe 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++ STLIn 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++ STLThe 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++ STLThe 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++ STLThe 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++ STLThe 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 Like