[英]How to count the number of distinct values in a C++ std::map<Key,Values>
I have a c++ map declared as follows我有一个 C++ 地图声明如下
std::map<std::string, int> wordMap= {
{ "is", 6 },
{ "the", 5 },
{ "hat", 9 },
{ "at", 6 }
};
I would like to know how to find the number of distinct values of int existing in wordMap.我想知道如何找到 wordMap 中存在的 int 不同值的数量。 In this example, I would expect an output of 3 as i have 3 different distinct values (6,5,9).在这个例子中,我希望输出为 3,因为我有 3 个不同的不同值 (6,5,9)。
Try to use std::set for counting:尝试使用 std::set 进行计数:
std::set<int> st;
for (const auto &e : wordMap)
st.insert(e.second);
std::cout << st.size() << std::endl;
One way is to store all keys of wordMap
in a set and then query its size:一种方法是将wordMap
所有键存储在一个集合中,然后查询其大小:
#include <unordered_set>
#include <algorithm>
std::map<std::string, int> wordMap= { /* ... */ };
std::unordered_set<int> values;
std::transform(wordMap.cbegin(), wordMap.cend(), std::insert_iterator(values, keys.end()),
[](const auto& pair){ return pair.second; });
const std::size_t nDistinctValues = values.size();
Note that in C++20, the above presumably boils down to请注意,在 C++20 中,上述内容大概可以归结为
#include <ranges>
#include <unordered_set>
const std::unordered_set<int> values = wordMap | std::ranges::values_view;
const std::size_t nDistinctValues = values.size();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.