C++ 如何计算地图中重复元素/值的数量?
例如,我如何找到“59”岁的人数?还有“64”?这些名字是不必要的 在输出中,我只需要年龄和重复次数。从这里开始,它是64->2和53->2倍。(此外,没有决定行数的整数。)C++ 如何计算地图中重复元素/值的数量?,c++,C++,例如,我如何找到“59”岁的人数?还有“64”?这些名字是不必要的 在输出中,我只需要年龄和重复次数。从这里开始,它是64->2和53->2倍。(此外,没有决定行数的整数。) 以下是一个简单的解决方案: #include <iostream> #include <map> #include <algorithm> #include <string> #include <unordered_map> using namespace st
以下是一个简单的解决方案:
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, size_t> counts;
std::map<std::string, int> m = {
{"XzbitYmay", 64},
{"Bruce Watson", 53},
{"Nim George", 53},
{"Lee Harry", 64},
{"Nim George", 59 }};
for(const auto& kvp : m) {
counts[kvp.second]++;
}
for(const auto& kvp: counts) {
if(kvp.second > 0)
std::cout << kvp.first << "->" << kvp.second << '\n';
}
return 0;
}
#包括
#包括
#包括。请展示您的最大努力,并就您的尝试提出具体问题。您想计算地图中出现的每个年龄的发生率,还是只计算一个特定(任意)年龄的发生率?
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, size_t> counts;
std::map<std::string, int> m = {
{"XzbitYmay", 64},
{"Bruce Watson", 53},
{"Nim George", 53},
{"Lee Harry", 64},
{"Nim George", 59 }};
for(const auto& kvp : m) {
counts[kvp.second]++;
}
for(const auto& kvp: counts) {
if(kvp.second > 0)
std::cout << kvp.first << "->" << kvp.second << '\n';
}
return 0;
}