Check if all values in a Map are Equal in C++

This tutorial will discuss how to check if all values in a map are equal in C++.

To check if all the values in a map are equal or not, we can first fetch the value of the first key-value pair in the map, and then we can compare this value with all the remaining key-value pairs in the map. If this value matches with all the key-value pairs’ value field, then it means all the values in the map are equal.

We have created a generic function for this.

template <typename Key, typename Value>
bool allValuesEqual(
    const std::map<Key, Value> &mapObj)
{
    bool result = !mapObj.empty();
    if (result)
    {
        const Value &firstValue = mapObj.begin()->second;
        for (const auto &pair : mapObj)
        {
            if (pair.second != firstValue)
            {
                result = false;
            }
        }
    }
    return result;
}

It accepts a map of any type as an argument and returns true if all the values in the map are equal.

Let’s see the complete example,

#include <iostream>
#include <map>

template <typename Key, typename Value>
bool allValuesEqual(
    const std::map<Key, Value> &mapObj)
{
    bool result = !mapObj.empty();
    if (result)
    {
        const Value &firstValue = mapObj.begin()->second;
        for (const auto &pair : mapObj)
        {
            if (pair.second != firstValue)
            {
                result = false;
            }
        }
    }
    return result;
}

int main()
{
    std::map<std::string, int> wordFrequency{
                                        {"this", 22},
                                        {"why",  22},
                                        {"what", 22},
                                        {"how",  22}};

    if (allValuesEqual(wordFrequency))
    {
        std::cout << "All values in Map are equal." << std::endl;
    }
    else
    {
        std::cout << "Values in Map are not all equal." << std::endl;
    }

    return 0;
}

Output

All values in Map are equal.

Summary

Today, we learned how to check if all values in a map are equal in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top