【问题标题】:Find number of occurrences in a map C++查找地图 C++ 中出现的次数
【发布时间】:2019-12-31 18:40:37
【问题描述】:

我正在尝试在 C++ 中创建一个映射,我将使用它来比较一个字符串向量是否与另一个向量匹配。条件是只能考虑一个词。例如,给定:

{"two", "times", "three", "is", "not", "four"}
{"two", "times", "two", "is", "four"}

在这种情况下,它们不应该匹配,因为第一个向量中只有一个 "two"

我的代码如下:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void checkMagazine(vector<string> magazineWords, vector<string> noteWords)
{
    map<string, int> magazine;
    map<string, int>::iterator it = magazine.begin();

    //populating the map
    for (string magazineWordString : magazineWords)
    {
        it = magazine.find(magazineWordString);

        if (it != magazine.end())
        {
            int numberOfOccurences = it->second;
            magazine.insert(pair<string, int>(magazineWordString, numberOfOccurences + 1));
        }
        else
        {
            magazine.insert(pair<string, int>(magazineWordString, 1));
        }
    }

    //checking for correspondences
    for (string noteWordString : noteWords)
    {
        it = magazine.find(noteWordString);

        if (it != magazine.end())
        {
            int numOfOccurences = it->second;
            magazine.insert(pair<string, int>(noteWordString, numOfOccurences - 1));
        }
        else
        {
            cout << "There is no match." << endl;
            return;
        }
    }

    cout << "There is a match!" << endl;
}

【问题讨论】:

  • 您能否详细说明您的“匹配”标准?也就是说,你能举出更多好的和坏匹配的例子吗?
  • @scohe001 向量magazineWords 必须具有noteWords 的所有元素才能匹配
  • 因此,如果在您的示例中,您表明magazineWords 必须具有noteWords 的所有元素,并且这些元素必须至少出现与noteWords 中相同的次数。对吗?
  • 如果键已经存在,插入具有相同键的新对不会更改映射。相反,使用迭代器访问该对并增加其计数。
  • @scohe001 正确,所以如果 noteWords = {"two", "times", "two", "is", "four"},那么 magazineWords 必须有两个 twos 匹配。

标签: c++ dictionary hashmap


【解决方案1】:

有一个更简单的方法!地图上的下标运算符将尝试在地图中查找键。如果成功,则返回对其值的引用。否则,它会在现场为您创建一个新的键/值对,并为您提供对 值的引用。

因此,由于int 的默认值为 0(即,当我们创建新的键/值对时,该值将为 0),所以您的所有工作实际上都可以是:

bool checkMagazine(vector<string> magazineWords, vector<string> noteWords)
{
    map<string, int> bank;

    //populating the map
    for (string magazineWord : magazineWords) {
        ++bank[magazineWord];
    }

    //checking for correspondences
    for (string noteWord : noteWords) {
        if(--bank[noteWord] < 0) { return false; }
    }

    return true;
}

在这里观看它的运行:https://ideone.com/MzLAJM

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多