【发布时间】: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