Searching a std::Map

What is the best way to search a std::Map for a specific key and value? Which basically means that I would like to find if exists a std::pair with key and value specified by me.

Upvotes: 0

Views: 478

Answers (4)

Stephane Rolland
Stephane Rolland

Reputation: 39906

For finding items on some criteria on values I usually use predicate functors with the std::find_if function.

#include <map>
#include <algorithm>
#include <string>

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

struct Predicate
{
    Predicate(const MyPair& myPair):m_myPair(myPair)
    {
    }

    bool operator() (const std::pair<int,std::string> aPair)
    {
        return aPair.first == m_myPair.first && aPair.second == m_myPair.second;

    }

    MyPair m_myPair;
};


void Test()
{
    MyMap myMap;

    MyPair aPair(0,std::string("aTest"));
    Predicate predicate(aPair);

    MyMap::iterator iter = std::find_if(myMap.begin(),myMap.end(),predicate);
}

Upvotes: 0

ROAR
ROAR

Reputation: 1324

Something like this ?

auto piter = m_mMap.find(iKey);

return pIter != m_mMap.end() && pIter->second == myvalue;

Upvotes: 4

Component 10
Component 10

Reputation: 10497

Since std::map is keyed uniquely, you only have to look for the key using find() and you'll have found the only instance, you can then compare your value against the one you find to check if the values compare favourably.

Don't make the mistake of using operator[] which will insert the value or replace it if it doesn't exist - probably not what you want.

Upvotes: 5

ssegvic
ssegvic

Reputation: 3142

std::map is a unique associative container, meaning that no two elements have the same key.

Thus, it suffices searching for the specific key by std::map::find.

Upvotes: 3

Related Questions