Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 888
Pat. ANDRIA Avatar asked Jun 07 '19 07:06

Pat. ANDRIA


People also ask

How do you count unique values in C++?

Using sort function() Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements.

How do you count the number of keys on a map?

Each element has a key value and a mapped value. No two mapped values can have same key values. In C++, size() function is used to return the total number of elements present in the map. Return Value: It returns the number of elements present in the map.

Can a Key have multiple values in map C++?

Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case.

Can there be duplicates in a map C++?

C++ Software Engineering Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.


1 Answers

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;
like image 200
gimme_danger Avatar answered Sep 24 '22 02:09

gimme_danger