c++stlstdstdmapstdset

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


Solution

  • 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;