I am trying to assign a custom type as a key for std::map
. Here is the type which I am using as key:
struct Foo
{
Foo(std::string s) : foo_va
The other answers already solve your problem, but I'd like to offer an alternative solution. Since C++11 you can use a lambda expression instead of defining operator<
for your struct
. (operator>
is not needed for your map to work.) Providing a lambda expression to the constructor of a map has certain advantages:
struct
that you want to store in your map.struct
as key.operator<
differently and use it for a different purpose.As a result, you can keep your struct
as short as follows:
struct Foo {
Foo(std::string s) : foo_value(s) {}
std::string foo_value;
};
And your map can then be defined in the following way:
int main() {
auto comp = [](const Foo& f1, const Foo& f2) { return f1.foo_value < f2.foo_value; };
std::map m({ {Foo("b"), 2}, {Foo("a"), 1} }, comp);
// Note: To create an empty map, use the next line instead of the previous one.
// std::map m(comp);
for (auto const &kv : m)
std::cout << kv.first.foo_value << ": " << kv.second << std::endl;
return 0;
}
Output:
a: 1
b: 2
Code on Ideone