Friday, March 20, 2009

c++ stl - fast way to check if map contains value

//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

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

typedef std::pair<std::string, int> MyPair;
typedef std::map<std::string, int> TestMap;

struct MapFind : public std::binary_function< MyPair, int, bool >
{
     bool operator()(const MyPair& p, int value) const
     {
         return p.second == value;
     }
};

int main(int argc, char** argv)
{
    TestMap testMap;
    testMap["a"] = 1;
    testMap["b"] = 2;
    testMap["c"] = 3;

    TestMap::iterator it;
    it = std::find_if(testMap.begin(), testMap.end(), std::bind2nd(MapFind(), 2));
    if (it != testMap.end())
    {
        std::cout  << " Found ! " 
                    << it->first << " " 
                    << it->second << std::endl;
    }
    else
    {
        std::cout << " Not Found ! " << std::endl;
    }

    return 0;
}