값을 반복하면서 값을 사용하여 HashMap에서 항목을 제거하는 방법에 대해 논의하십시오. 예를 들어
Input: HashMap: { 1: “ Mango ”,
2: “ Orange ”,
3: “ Banana ”,
4: “Apple ” }, value=”Banana”
Output: HashMap: { 1: “ Mango ”,
2: “ Orange ”,
4: “Apple ” }.
Explanation: The third key-value pair is removed using the value “banana”.
Input: HashMap: { 1: “Yellow”,
2: “White”,
3: “Green” }, value=”White”
Output: HashMap: { 1: “Yellow”,
3: “Green” }. 해결책을 찾기 위한 접근 방식
C++에서는 .erase() 함수를 사용하여 요소를 제거할 수 있습니다. Erase() 함수에서 키 이름을 사용하거나 반복자를 사용하여 요소를 제거할 수 있습니다. 이 자습서에서는 반복자를 사용하여 요소를 제거하는 방법에 대해 설명합니다.
여기서 우리는 해시맵을 반복하고 모든 값이 제거되었는지 확인하고 값이 일치하면 항목을 제거합니다.
예시
위 접근 방식에 대한 C++ 코드
HashMap을 반복하는 동안 요소 제거
#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){
// Creating HashMap.
map< int, string > fruits;
// Inserting key-value pair in Hashmap.
fruits[1]="Mango";
fruits[2]="Orange";
fruits[3]="Banana";
fruits[4]="Apple";
string value = "Banana";
// Creating iterator.
map<int, string>::iterator it ;
// Printing the initial Hashmap.
cout<< "HashMap before Deletion:\n";
for (it = fruits.begin(); it!=fruits.end(); ++it)
cout << it->first << "->" << it->second << endl;
for (it = fruits.begin(); it!=fruits.end(); ++it){
string temp = it->second;
// Checking iterator value with required value.
if(temp.compare(value) == 0){
// erasing Element.
fruits.erase(it);
}
}
// Printing Hashmap after deletion.
cout<< "HashMap After Deletion:\n";
for (it = fruits.begin(); it!=fruits.end(); ++it)
cout << it->first << "->" << it->second << endl;
return 0;
}
출력
HashMap before Deletion: 1->Mango 2->Orange 3->Banana 4->Apple HashMap After Deletion: 1->Mango 2->Orange 4->Apple
결론
이 자습서에서는 값을 사용하여 HashMap에서 항목을 제거하는 방법에 대해 설명했습니다. 항목을 반복하여 항목을 제거하는 방법에 대해 논의했습니다. 우리는 또한 C, Java, Python 등과 같은 프로그래밍 언어로 할 수 있는 이 문제에 대한 C++ 프로그램에 대해 논의했습니다. 이 튜토리얼이 도움이 되기를 바랍니다.