开发者

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:开发者_JAVA技巧:pair with key and value specified by me.


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.


Something like this ?

auto piter = m_mMap.find(iKey);

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


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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜