从 unordered_map 中删除单个节点

Remove single node from unordered_map

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

#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 中删除该单个节点(或仅该特定单词的单个实例),但据我所知,唯一可以做到这一点的修饰符是 'extract' 但 我不能使用 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";