从unordered_map删除单个节点

问题描述 投票:0回答:2

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

#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?链表会更合适吗?我是数据结构的新手,所以将不胜感激。

c++ unordered-map
2个回答
1
投票

具有这种性质的东西。我写的时候没有多加思考,也没有检查,所以随便拿一点盐(可能是正确的)。想法是使用单词在杂志中出现的次数计数,并从您在便笺中找到它时减去它。

    unordered_map<string, int> mp;
    for(auto s: magazine) mp[s]++;
    for(auto s: note) {
        int count = mp[s];
        if(!count) { cout << "No"; return; }
        mp[s]--; count--; 
        if(!count) mp.erase(s);
    }
    cout << "Yes";

0
投票

解决问题的另一种方法是从杂志中创建一组单词。然后遍历note中的单词并检查它们是否都出现在集合中。

void checkMagazine(std::vector<string> magazine, std::vector<string> note) {

    // Create set of magazine words
    std::set<std::string> magazineWords{ magazine.cbegin(), magazine.cend() };

    // For each word in note search the set for that word
    for (auto& word : note) {
        auto it = magazineWords.find(word);
        if (it == magazineWords.end()) { // Word not in magazine
            std::cout << "No" << std::endl;
            return;
        }
    }

    std::cout << "Yes" << std::endl;
}

这可以避免不必要地删除容器中的元素。

© www.soinside.com 2019 - 2024. All rights reserved.