首页 > 解决方案 > 是否可以在 C++ 中声明两个变量 For-Each 循环?

问题描述

我正在尝试编写一个可以检查的函数,如果两个字符串具有相同频率的所有字符。所以为了做到这一点,我尝试制作两个地图,即unordered_map<char, int>. 所以在我的下一步中,我只想比较char地图上每个值的每个值。

string A;
string B;

unordered_map<char, int> a;
unordered_map<char, int> b;

for (char i : A)
{
    a[i]++;
}
for (char i : B)
{
    b[i]++;
}
for (char i : A &&char j : B)
{
    //code goes here
}

那么,是否有可能有一个带有两个不同变量的 For-Each 循环?

标签: c++

解决方案


我将绕过您的for循环问题,说您是否想知道两个映射是否包含您可以使用的相同键值元素std::unordered_map::operator==

unordered_map<char, int> a;
unordered_map<char, int> b;

for (char i : A)
{
    a[i]++;
}
for (char i : B)
{
    b[i]++;
}
if (a == b) // this does the right thing
{
    // the frequencies are the same
}

推荐阅读