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() 函数中,我们可以使用键名或使用迭代器移除元素。在本教程中,我们将讨论如何使用迭代器移除元素。
这里我们将遍历哈希表并检查是否已移除每个值,并在值匹配时移除条目。
示例
上述方法的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++程序,它可以使用C、Java、Python等编程语言完成。我们希望本教程对您有所帮助。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP