从unordered_map中删除单个节点

Remove single node from unordered_map

本文关键字:删除 单个 节点 map unordered      更新时间:2023-10-16

如果注释中包含的所有单词都出现在杂志中(区分大小写(,程序应打印"是",否则打印"否"。杂志中的每个单词只能使用一次,也就是说,如果注释有两次相同的单词,则杂志也必须至少包含该单词两次。

#include<iostream>
#include<vector>
#include<string>
#include<unordered_map>
using namespace std;
void checkMagazine(vector<string> magazine, vector<string> note) {
// Inserts magazine vector into an unordered_map for quick access
unordered_map<string, int> umap;
for (auto& x : magazine)
umap[x] = 1;    
// For each word in note search the unordered_map for that word
for (auto& word : note) {
if (umap.find(word) == umap.end()) { // Word not in magazine
cout << "No" << endl;
return;
}
else    // Remove single instance of that word
umap.erase(word);
}
cout << "Yes" << endl;
return;
}

int main()
{
vector<string> magazine = { "Help", "me", "please", "please" };
vector<string> note = { "Help", "please", "please" };
checkMagazine(magazine, note);
return 0;
}

else 条件需要从 umap 中删除该单个节点(或仅删除该特定单词的单个实例(,但据我所知,唯一可以做到这一点的修饰符是"提取",但我不能使用 C++17

有没有办法解决这个问题,或者这种类型的方法不适用于unordered_map? 链表会更合适吗?我是数据结构的新手,所以任何帮助将不胜感激。

这种性质的东西。我写的没有太多思考,也没有检查,所以对它持保留态度(可能是正确的(。这个想法是使用一个单词在杂志中出现的次数,并在您在注释中找到它时减去它。

unordered_map<string, int> mp;
for(const auto& s: magazine) mp[s]++;
for(const auto& s: note) {
auto it = mp.find(s);
if(it == mp.end() || it->second <= 0) { cout << "No"; return; }
it->second--; // if(!--it->second) mp.erase(it);  
if(!it->second) mp.erase(it); 
}
cout << "Yes";