7

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).

Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27

2 Answers2

9

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;
Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
gimme_danger
  • 788
  • 1
  • 6
  • 14
4

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();
lubgr
  • 37,368
  • 3
  • 66
  • 117