如何计算 C++ std::map<Key,Values> 中不同值的数量 [英] How to count the number of distinct values in a C++ std::map&lt;Key,Values&gt;

查看:22
本文介绍了如何计算 C++ std::map<Key,Values> 中不同值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C++ 映射声明如下

I have a c++ map declared as follows

std::map<std::string, int> wordMap= {
    { "is", 6 },
    { "the", 5 },
    { "hat", 9 },
    { "at", 6 } 
    };

我想知道如何找到 wordMap 中存在的 int 不同值的数量.在此示例中,我希望输出为 3,因为我有 3 个不同的不同值 (6,5,9).

I would like to know how to find the number of distinct values of int existing in wordMap. In this example, I would expect an output of 3 as i have 3 different distinct values (6,5,9).

推荐答案

尝试使用 std::set 进行计数:

Try to use std::set for counting:

std::set<int> st;
for (const auto &e : wordMap)
  st.insert(e.second);
std::cout << st.size() << std::endl;

这篇关于如何计算 C++ std::map<Key,Values> 中不同值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆