C ++在map中使用.find()和struct作为键 [英] C++ Using .find() with struct as key in map

查看:519
本文介绍了C ++在map中使用.find()和struct作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我没有访问BOOST或STL我的结构和映射看起来类似于下面的伪装:

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

我想要做的是搜索我的多重映射的所有情况,其中A = 2,B = 2或A& B = 2.我不是很确定,但我想我需要在我的结构中创建谓词查找。想要

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?

推荐答案

运算符< $ c> find 或任何其他。但是,您的实现有一个错误。

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

找到 true >和其他标准库组件使用假设 a == b iff! (a< b)&& ! (b ,因此如果 a b 相等, c $ c>< 必须 false 才能使用 find 。 >

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
        }

这篇关于C ++在map中使用.find()和struct作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆