How to remove a key from map in C++?

Member

by zita , in category: C/C++ , 2 years ago

How to remove a key from map in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dee_smith , 2 years ago

@zita You can use the erase() function to remove any key from a map in C++. Below is the code as an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<bits/stdc++.h>

int main() {
    std::map<int, std::string> m;

    m[1] = "C++";
    m[2] = "Java";
    m[3] = "PHP";

    // Output: 3
    std::cout << m.size() << std::endl;

    // Remove a key 2 from map
    m.erase(2);

    for (const auto &p: m) {
        std::cout << p.first << '\t' << p.second << std::endl;
    }
    // Output:
    // 1   C++
    // 3   PHP
    
    return 0;
}


Member

by hailie , a year ago

@zita 

In C++, you can remove a key from a map container using the erase() method. The erase() method takes an iterator to the element to be removed, so you need to first locate the element using the find() method or some other means.


Here's an example code snippet that demonstrates how to remove a key-value pair from a map container:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
    int keyToRemove = 2;

    // Find the element to remove using the find() method
    auto it = myMap.find(keyToRemove);

    // Check if the element was found
    if (it != myMap.end()) {
        // Remove the element using the erase() method
        myMap.erase(it);
        std::cout << "Element with key " << keyToRemove << " removed from map." << std::endl;
    } else {
        std::cout << "Element with key " << keyToRemove << " not found in map." << std::endl;
    }

    return 0;
}


In this example, we create a std::map container with some key-value pairs. We then specify a key to remove, and use the find() method to locate the element with that key. If the element is found, we remove it using the erase() method and print a message indicating success. If the element is not found, we print a message indicating failure.