gpt4 book ai didi

c++ - 特定键在 std::multimap 中出现了多少次

转载 作者:行者123 更新时间:2023-11-27 23:53:56 25 4
gpt4 key购买 nike

我正在使用 C++ 处理多映射数据类型,我想知道特定键在我的映射中存在了多少次。下一个例子将解释我在寻找什么:

#include <iostream>
#include <map>

int main ()
{
std::multimap<char,int> mymap;
mymap.insert ({'c',10});
mymap.insert ({'y',20});
mymap.insert ({'c',30});
mymap.insert ({'z',40});
mymap.insert ({'c',40});


std::cout << "mymap.size() is " << mymap.size() << '\n';

return 0;
}

上面的代码会给我 map 中唯一键的数量,这不是我要找的。

    #include <iostream>
#include <map>

int main ()
{
std::multimap<char,int> mymap;

mymap.insert ({'c',10});
mymap.insert ({'y',20});
mymap.insert ({'c',30});
mymap.insert ({'z',40});
mymap.insert ({'c',40});

std::cout << "mymap.size('c') is " << mymap.size('c') << '\n';

return 0;
}

我想要一种机制来计算键“c”在我的 map 中重复了多少次。前面例子的正确答案是 3。

最佳答案

使用 mymap.count('c')。如果您想遍历具有相同键的元素,请使用 equal_range 方法。

关于c++ - 特定键在 std::multimap 中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44043438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com