Pat. ANDRIA
Pat. ANDRIA

Reputation: 2412

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

I have a c++ map declared as follows

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. In this example, I would expect an output of 3 as i have 3 different distinct values (6,5,9).

Upvotes: 7

Views: 2271

Answers (2)

gimme_danger
gimme_danger

Reputation: 798

Try to use std::set for counting:

std::set<int> st;
for (const auto &e : wordMap)
  st.insert(e.second);
std::cout << st.size() << std::endl;

Upvotes: 9

lubgr
lubgr

Reputation: 38267

One way is to store all keys of wordMap in a set and then query its size:

#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

#include <ranges>
#include <unordered_set>

const std::unordered_set<int> values = wordMap | std::ranges::values_view;
const std::size_t nDistinctValues = values.size();

Upvotes: 4

Related Questions