如何计算C++中非重复值的数量 std::map<Key,Values>

How to count the number of distinct values in a C++ std::map<Key,Values>

本文关键字:gt std map Values Key lt 计算 何计算 C++      更新时间:2023-10-16

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

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

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

尝试使用 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();