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.
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?