Question

I have a map like this with enum as key and UINT as value.

    #include <iostream>
    #include <string>
    #include <map>

    using namespace std;

    typedef enum tcGroup_t
    {
        CG_NONE      = 0,
        CG_BASE      = 1, 
        CG_RC        = 3,
        CG_HTD       = 4,
        CG_HID       = 5
    } tcGroup;


    int getMaxtcGroupCount() 
    {
        std::map<tcGroup, UINT> maxTcGroup;
        maxTcGroup [CG_BASE] = 2;
        maxTcGroup [CG_HID]  = 33;
        maxTcGroup [CG_HTD]  = 44;
        maxTcGroup [CG_RC]   = 87;
        maxTcGroup [CG_NONE] = 39;
    }

Basically, I want to return the highest value in the map to the calling function. In the above case I want to return value 87. I know maps are ordered by means of Key, but in my case I want to return the highest value in the map?

Any help is appreciated. Thanks

Was it helpful?

Solution

You can use std::max_element with a suitable functor.

bool cmp(const std::pair<const tcGroup, UINT>& rhs,
         const std::pair<const tcGroup, UINT>& lhs)
{
  return rhs.second < lhs.second;
}

Then

auto max_iter = max_element(maxTcGroup.begin(), maxTcGroup.end());

OTHER TIPS

You can use std::max_element with a custom comparator:

#include <map>
#include <algorithm>
#include <iostream>
#include <cassert>

int main()
{
    typedef std::map<char, int> M;

    M m;
    m['a'] = 5;
    m['b'] = 8;
    m['c'] = 2;

    M::const_iterator it = std::max_element(
        std::begin(m), std::end(m),
        [](M::value_type& lhs, M::value_type& rhs) {
            return lhs.second < rhs.second;
        }
    );

    assert(it != m.end());
    std::cout << it->first << '\n';  // 'b'
}

Live demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top