簡體   English   中英

如何計算 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM