0

This is my first post - sorry if I mess any of the site's conventions. Please point out any mistakes I make so i could fix them/not repeat them.

This post may be related

c++ reference: std::map

c++ reference: std::map - rational operators

I want to be able to use std::map's operator[] by putting an std::string between the brackets - even though the key of the map isn't std::string.

here's the code

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

So far this works fine - but as you can see, the only thing the operator uses is the std::string _name field of the class. I wan't to be able to look up a value in the map, by only entering a string like so: map["keyString"].

I have tried overloading the operator< of myKey, but it didn't help.

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

How can it be done?

Community
  • 1
  • 1
alon sirota
  • 57
  • 1
  • 7

2 Answers2

1

"" is a string literal, of type const char*. The reason why it doesn't work when you do map["keyString"] is because "keyString" first has to be converted to a std::string, and then it can be passed as a key.

But because it has to be converted (to std::string) first, this is illegal.

You can just add a constructor which takes a const char*:

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

If you don't want to add a new constructor, you can use 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;
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
0

Thanks rakete - you pointed out the problem. But there's a simpler solution: The steps:

  1. Overload the operator< with a method that takes the parameter you want (in this case, std::string. Make sure you are using the correct signature of the function checkout my operator< functions

  2. When trying to get a value in the map using operator[] make sure you enter the right value between the brackets (this is what I did wrong, entered a string literal like this - map["keyString"] instead of entering an std::string like this - map[std::string("keyString")]

alon sirota
  • 57
  • 1
  • 7