如何计算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,因为我(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();
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- std::map<std::set, double> AND std:<long>map< std::p air<long, long>, double>
- 如何获取std::vector<DMatch>