C++ 從 HashMap 中使用鍵遍歷時移除項


本教程將討論如何在遍歷 HashMap 時使用鍵從中移除項。例如,

Input: HashMap: { 1: “Tutorials”,
                  2: “Tutorials”,
                  3: “Point” }, key=1

Output: HashMap: { 2: “Tutorials”,
                   3: “Point” }.

Explanation: The first element is removed using key ‘1’.

Input: HashMap: { 1: “God”,
                  2: “is”,
                  3: “Great” }, key=2

Output: HashMap: { 1: “God”,
                   3: “Great” }.

尋找解決方案的方法

在 C++ 中,我們可以使用 .erase() 函式中的鍵名來使用鍵移除項。但在此,我們需要在遍歷時移除項,因此還需要一個迭代器。

在此,我們將遍歷 HashMap 並檢查每個鍵是否已移除,並在鍵匹配時移除該項。

例項

上述方法的 C++ 程式碼

不進行遍歷

以下是移除元素而不遍歷 HashMap 的程式碼。

#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){  
    // Creating HashMap.
    map< int, string > mp;
    // Inserting key-value pair in Hashmap.
    mp[1]="Tutorials";
    mp[2]="Tutorials";
    mp[3]="Point";
    int key = 2;
    // Creating iterator.
    map<int, string>::iterator it ;
    // Printing the initial Hashmap.
    cout<< "HashMap before Deletion:\n";
    for (it = mp.begin(); it!=mp.end(); ++it)
        cout << it->first << "->" << it->second << endl;
    mp.erase(key);
    // Printing Hashmap after deletion.
    cout<< "HashMap After Deletion:\n";
    for (it = mp.begin(); it!=mp.end(); ++it)
        cout << it->first << "->" << it->second << endl;
    return 0;
}

輸出

HashMap before Deletion:
1->Tutorials
2->Tutorials
3->Point

HashMap After Deletion:
1->Tutorials
3->Point

例項

遍歷 HashMap 時移除元素

#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){  
    // Creating HashMap.
    map< int, string > mp;
    // Inserting key-value pair in Hashmap.
    mp[1]="Tutorials";
    mp[2]="Tutorials";
    mp[3]="Point";
    int key = 2;
    // Creating iterator.
    map<int, string>::iterator it ;
    // Printing the initial Hashmap.
    cout<< "HashMap before Deletion:\n";
    for (it = mp.begin(); it!=mp.end(); ++it)
        cout << it->first << "->" << it->second << endl;
        // Iterating over HashMap.
    for (it = mp.begin(); it!=mp.end(); ++it){
        int a=it->first;
        // Checking iterator key with required key.
        if(a==key){
            // erasing Element.
            mp.erase(it);
        }
    }
    // Printing Hashmap after deletion.
    cout<< "HashMap After Deletion:\n";
    for (it = mp.begin(); it!=mp.end(); ++it)
        cout << it->first << "->" << it->second << endl;
    return 0;
}

輸出

HashMap before Deletion:
1->Tutorials
2->Tutorials
3->Point

HashMap After Deletion:
1->Tutorials
3->Point

結論

在本教程中,我們討論瞭如何從 HashMap 中移除項。我們討論了兩種移除項的方法,即遍歷 HashMap 和不遍歷 HashMap。我們還討論了這個問題的 C++ 程式,我們可以用 C、Java、Python 等程式語言編寫該程式。我們希望本教程對你有所幫助。

更新於: 2021 年 11 月 26 日

800 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告