이 자습서에서는 키를 탐색하는 동안 키를 사용하여 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() 함수에서 키 이름을 사용하여 키를 사용하여 항목을 제거할 수 있습니다. 하지만 여기서는 반복하는 동안 제거해야 하므로 반복자도 필요합니다.
여기에서 해시맵을 반복하고 모든 키가 제거되었는지 확인하고 키가 일치하면 항목을 제거합니다.
예시
위 접근 방식에 대한 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에서 항목을 제거하는 방법에 대해 설명했습니다. 항목을 반복하는 항목과 반복하지 않는 항목을 제거하는 두 가지 방법에 대해 설명했습니다. 우리는 또한 C, Java, Python 등과 같은 프로그래밍 언어로 할 수 있는 이 문제에 대한 C++ 프로그램에 대해 논의했습니다. 이 튜토리얼이 도움이 되기를 바랍니다.