C++ Using .find() with struct as key in map

↘锁芯ラ 提交于 2019-12-12 11:28:35

问题


All I do not have access to BOOST or STL my struct and map looks similar to the following psuedo:

 struct s_map_key{
    int a;
    int b;
    bool operator<(const s_map_key& smk) const 
    {
        if (a < smk.a)       
        {            
            return true;
        } else if (a == smk.a)  
        { 
            if (b < smk.b) 
            { 
                return true;
            } 
            else if (b == smk.b)
            {
                return true;
            }
        } 
            return false;
    }
};

int main(int argc, char* argv[])
{

    std::multimap<s_map_key, std::string> myMap;
    for(int i = 0; i <10; i++)
    {
    s_map_key smk;
    smk.a = i;
    smk.b = 2;
    myMap.insert(std::make_pair(smk, "test"));
    }

    s_map_key smk;
    smk.a = 3;
    std::multimap<s_map_key, std::string>::iterator x = myMap.find(smk);
    if(x != myMap.end())
    {
        std::cout << x->first.a <<std::endl;
        std::cout << x->first.b <<std::endl;
    }
    return 0;
}

What I am trying to do is search my multimap for all cases where A = 2, B = 2, or A & B = 2. I am not exactly sure but, I think i need to create the predicates in my struct for "finding". Ideas?


回答1:


operator< is all you need for find or anything else. However, your implementation has a bug. It returns true if the operands are equal.

find and other Standard Library components use the assumption that a == b iff ! (a < b) && ! (b < a), so if a and b are equal, < must be false for find to work.

        else if (b == smk.b)
        {
            return false; // was true
        }



回答2:


Unless you want to establish an equivalence of 2 == smk if (smk.a == 2 || smk.b == 2 || smk.a & smk.b == 2), I suggest making the predicate external and using std::find_if. If you make it part of the struct so that you can use multimap's internal find function, you could open the door for the predicate being used in an undesired way by another coder. Also, the internal find function will only return the first instance that matches, whereas with std::find_if you can update your starting point so that you can find all instances. If you want to use the internal functions, you'll need to use equal_range instead.



来源:https://stackoverflow.com/questions/5655179/c-using-find-with-struct-as-key-in-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!