C ++在迭代时使用HashMap中的值删除条目
例如,讨论如何在迭代时使用该值从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()函数中,我们可以使用键名或使用迭代器删除元素。在本教程中,我们将讨论使用迭代器删除元素。
在这里,我们将遍历hashmap并检查是否每个值都被删除,并在值匹配时删除条目。
示例
上述方法的C++代码
迭代HashMap时删除元素
#include<iostream>
#include<map> //用于映射操作
using namespace std;
int main(){
//创建哈希映射。
map< int, string > fruits;
//在Hashmap中插入键值对。
fruits[1]="Mango";
fruits[2]="Orange";
fruits[3]="Banana";
fruits[4]="Apple";
string value = "Banana";
//创建迭代器。
map<int, string>::iterator it ;
//打印初始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;
//使用所需值检查迭代器值。
if(temp.compare(value) == 0){
//擦除元素。
fruits.erase(it);
}
}
//删除后打印Hashmap。
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++程序,我们可以使用C、Java、Python等编程语言来解决这个问题。我们希望本教程对您有所帮助。