繁体   English   中英

std :: map:用除键类以外的参数重载operator <

[英]std::map: overloading the operator< with a parameter other than the key's class

这是我的第一篇文章-很抱歉,如果我弄乱了网站的任何约定。 请指出我犯的任何错误,以便我可以解决/不重复。

这个帖子可能与

C ++参考:std :: map

C ++参考:std :: map-有理运算符

我希望能够通过将std::string放在方括号之间来使用std::mapoperator[] -即使map的键不是std::string

这是代码

class myKey
{
public:
    std::string _name;

    myKey(std::string name)
    {
        _name = name;
    }

    bool operator<(const myKey& other) const
    {
        if (this->_name < other._name)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

int main()
{
    std::map<myKey, int> map;
    myKey temp("keyString");
    map[temp] = 1;
    std::cout << map[temp];

    system("pause");
    return 0;
}

到目前为止,它可以正常工作-但如您所见,操作员唯一使用的是该类的std::string _name字段。 我仅通过输入像这样的字符串就无法在地图中查找值: map["keyString"]

我尝试重载myKeyoperator< ,但没有帮助。

bool operator<(const std::string name) const
{
    if (this->_name < name)
    {
        return true;
    }
    else
    {
        return false;
    }
}

如何做呢?

""是字符串文字,类型为const char* 当您执行map["keyString"]时,它不起作用的原因是因为"keyString"首先转换为std::string ,然后才能作为键传递。

但是因为必须先将其转换(转换为std::string ),所以这是非法的。

您可以只添加一个接受const char*的构造const char*

myKey(const char* name) : _name{ name } {}

如果您不想添加新的构造函数,则可以使用std::string_literals::operator""s

using namespace std::string_literals;

//Note 's' after "", this means that "keyString" is of type std::string, not const char*
map["keyString"s] = 1;

感谢rakete-您指出了问题所在。 但是有一个更简单的解决方案:步骤:

  1. 使用采用所需参数的方法重载operator< (在这种情况下,为std::string 。请确保您使用的是函数的正确签名)签出myoperator operator<函数

  2. 当尝试使用operator[]在地图中获取值时,请确保在括号之间输入正确的值(这是我做错的,请输入如下string literal map["keyString"]而不是输入std::string像这样map[std::string("keyString")]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM