如何计算 C++ 中不同值的数量 std::map<Key,Values>
How to count the number of distinct values in a C++ std::map<Key,Values>
我有一个声明如下的c++映射
std::map<std::string, int> wordMap= {
{ "is", 6 },
{ "the", 5 },
{ "hat", 9 },
{ "at", 6 }
};
我想知道如何找到 wordMap
中存在的 int
的不同值的数量。
在此示例中,我希望输出为 3,因为我有 3 个不同的不同值 (6,5,9)
.
尝试使用std::set
进行计数:
std::set<int> st;
for (const auto &e : wordMap)
st.insert(e.second);
std::cout << st.size() << std::endl;
一种方法是将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();
请注意,在 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();
我有一个声明如下的c++映射
std::map<std::string, int> wordMap= {
{ "is", 6 },
{ "the", 5 },
{ "hat", 9 },
{ "at", 6 }
};
我想知道如何找到 wordMap
中存在的 int
的不同值的数量。
在此示例中,我希望输出为 3,因为我有 3 个不同的不同值 (6,5,9)
.
尝试使用std::set
进行计数:
std::set<int> st;
for (const auto &e : wordMap)
st.insert(e.second);
std::cout << st.size() << std::endl;
一种方法是将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();
请注意,在 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();