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

0

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.