SoFunction
Updated on 2025-04-14

How to use C++ std:map

std::mapIt is a powerful and efficient association container in the C++ standard library, providing key-value pair storage, automatic sorting and efficient search functions. In actual development,std::mapVery practical in scenarios where orderly storage and quick retrieval are required. This article will be analyzed in detailstd::mapThe functions and usage of  and code samples are provided to help you better grasp it.

1. What is std::map

std::mapyesC++ STL(Standard Template LibraryOne of the associated containers provides a storage form of key-value pairs, where each key is unique and arranged in order. Specifically:

  • Key: Each key is unique and is used to find a specific value.
  • Value: The content corresponding to the key, that is, the data to be stored

Why use std::map

  • Quick search:std::map is implemented using a balanced binary tree (usually a red-black tree) with O(logn) search, insertion and deletion efficiency.
  • Automatic sorting:std::map will automatically arrange in ascending order in keys, saving the hassle of manual sorting.
  • Key Uniqueness: Duplicate keys are not allowed in the same map, which makes it suitable for storing unique key-value pairs.

2. Basic usage of std::map

2.1 Defining and Initializing std::map

std::map can be defined and initialized in a variety of ways. Common definition methods are as follows:

#include <iostream>
#include <map>
using namespace std;

int main() {
    // Define a map with a key int and a value of string    map<int, string> studentMap;

    // Use the initialization list to initialize the map directly    map<int, string> employeeMap = {
        {1, "Alice"},
        {2, "Bob"},
        {3, "Charlie"}
    };

    return 0;
}

2.2 Insert elements

std::map provides two ways of inserting: using the insert method and the [ ] operator.

map<int, string> studentMap;

// Method 1: Use insert to insert key-value pairs({1, "Alice"});

// Method 2: Use the [] operator to insert it directlystudentMap[2] = "Bob";

// Output all key-value pairsfor (const auto &entry : studentMap) {
    cout <<  << ": " <<  << endl;
}

  • The insertion method using the [ ] operator is more convenient, and if the key already exists, the corresponding value will be updated.

2.3 Find elements

Use the find function to find a specific key. If found, it returns an iterator pointing to the element, otherwise it returns a map::end() iterator.
auto is an automatic type derivation keyword introduced in C++11, which allows the compiler to automatically deduce the types of variables.

auto it = (1);  // Find elements with key 1if (it != ()) {
    cout << "Found: " << it->second << endl;
} else {
    cout << "Not found!" << endl;
}

2.4 Delete elements

std::map provides a variety of ways to delete: key-click deletion, iterator-click, and delete elements in a specific range.

// key deletion(1);

// Press iterator to deleteauto it = (2);
if (it != ()) {
    (it);
}

3. Detailed explanation of common functions of std::map

3.1 Size and check whether it is empty: size and empty

  • size: Returns the number of key-value pairs in map.
  • empty: determine whether map is empty.
cout << "Size: " << () << endl;
if (()) {
    cout << "Map is empty" << endl;
}

3.2 Traversing std::map

A common way to traverse maps is to use scope-based for loops or iterators.

//The scope of use is based on for loopfor (const auto &amp;entry : studentMap) {
    cout &lt;&lt;  &lt;&lt; ": " &lt;&lt;  &lt;&lt; endl;
}

// Use an iteratorfor (auto it = (); it != (); ++it) {
    cout &lt;&lt; it-&gt;first &lt;&lt; ": " &lt;&lt; it-&gt;second &lt;&lt; endl;
}

3.3 Number of statistics keys: count

The count function returns the number of specific keys, which is unique for std::map, so the result is either 0 or 1.

if ((2) > 0) {
    cout << "Key 2 exists" << endl;
}

3.4 Get range: lower_bound and upper_bound

  • lower_bound: Returns the first iterator that is not smaller than the specified key.
  • upper_bound: Returns the first iterator larger than the specified key.
map&lt;int, string&gt; employeeMap = {
    {1, "Alice"},
    {3, "Bob"},
    {5, "Charlie"}
};

// Get rangeauto lb = employeeMap.lower_bound(3);  // Point the position of key 3auto ub = employeeMap.upper_bound(3);  // Point the position of key 5if (lb != ()) {
    cout &lt;&lt; "Lower bound: " &lt;&lt; lb-&gt;first &lt;&lt; endl;
}
if (ub != ()) {
    cout &lt;&lt; "Upper bound: " &lt;&lt; ub-&gt;first &lt;&lt; endl;
}

3.5 Clear map

The clear function clears all elements in the map.

();
if (()) {
    cout << "Map is now empty" << endl;
}

3.6 Sort

An important feature of std::map is automatic sorting, that is, after inserting a new element, map will be arranged in ascending order of the keys. We don't need to sort or manage order manually, std::map will always maintain internal order. Let's take a look at how this feature is reflected, and practical examples show the automatic sorting of std::map.

3.6.1 Automatic sorting example

When we insert elements into the map, the map will be stored in ascending order. Even if the insertion order is random, the output order of key-value pairs during traversal is still orderly.

#include &lt;iostream&gt;
#include &lt;map&gt;
using namespace std;

int main() {
    map&lt;int, string&gt; studentMap;

    // Insert elements in random order    studentMap[3] = "Charlie";
    studentMap[1] = "Alice";
    studentMap[4] = "Diana";
    studentMap[2] = "Bob";

    // traverse and print elements to observe the output order    cout &lt;&lt; "List of students (Automatically sort by ascending order of student number):" &lt;&lt; endl;
    for (const auto &amp;entry : studentMap) {
        cout &lt;&lt; "Student number: " &lt;&lt;  &lt;&lt; ", Name: " &lt;&lt;  &lt;&lt; endl;
    }

    return 0;
}

3.6.2 Custom sorting (advanced usage)

In addition to the default ascending order arrangement, std::map also allows custom sorting. When defining maps, you can pass in custom comparison functions to sort in descending order or other rules.

#include &lt;iostream&gt;
#include &lt;map&gt;
#include &lt;string&gt;
using namespace std;

// Custom comparison functions, sort in descending orderstruct DescendingOrder {
    bool operator()(const int &amp;a, const int &amp;b) const {
        return a &gt; b;
    }
};

int main() {
    map&lt;int, string, DescendingOrder&gt; studentMap;

    // Insert element    studentMap[3] = "Charlie";
    studentMap[1] = "Alice";
    studentMap[4] = "Diana";
    studentMap[2] = "Bob";

    // Output the content of the map    cout &lt;&lt; "List of students (Sort by descending order of student number):" &lt;&lt; endl;
    for (const auto &amp;entry : studentMap) {
        cout &lt;&lt; "Student number: " &lt;&lt;  &lt;&lt; ", Name: " &lt;&lt;  &lt;&lt; endl;
    }

    return 0;
}

Here, we define a comparison function DescendingOrder and pass it in as the third template parameter of the map, so that the map is arranged in descending order. This way, we can easily adjust the sorting of maps.

4. Notes on using std::map

Performance considerationsstd::map is implemented using a balanced binary tree, so the time complexity of search, insertion, and deletion is O(logn). If your data needs to be inserted or deleted frequently and is not sensitive to the order of keys, you can consider unordered_map, which has a time complexity of O(1).
Default construct key-value pairsWhen using the [] operator to find a key, if the key does not exist, std::map will automatically insert the key and set it to the default value. This can cause an error when unintentionally accessing a non-existent key.

map&lt;int, int&gt; numbers;
numbers[5] += 1;  // If key 5 Does not exist,Then it will be created and initialized as 0,Then add 1

5. Classic example: Statistics word frequency

Here is an example of using std::map to count the frequency of word occurrence in text:

#include &lt;iostream&gt;
#include &lt;map&gt;
#include &lt;string&gt;
#include &lt;sstream&gt;
using namespace std;

int main() {
    map&lt;string, int&gt; wordCount;
    string text = "this is a sample text with sample words and sample frequencies";
    
    stringstream ss(text); // Put the string text into the stringstream    string word;
    while (ss &gt;&gt; word) { // Extract words one by one from ss and store them to word        wordCount[word]++; // Statistics the number of occurrences of each word    }
    
    for (const auto &amp;entry : wordCount) {
        cout &lt;&lt;  &lt;&lt; ": " &lt;&lt;  &lt;&lt; endl;
    }
    return 0;
}

This is the end of this article about how to use C++ std:map. For more related content on using C++ std:map, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!