I’m reading the std::map part of The C++ Standard Library by Nicolai M. Josuttis.
Here is a simplified code which can show the question bother me a lot:
#include <iostream>
#include <map>
#include <string>
class MyCompare {
public:
bool operator() (const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
};
int main() {
std::map<std::string, int, MyCompare> m {{"foo", 1}, {"bar", 2}, {"baz", 3}};
for (const auto& p : m) {
std::cout << p.first << " -> " << p.second << std::endl;
}
return 0;
}
As you can see, I use my own MyCompare to show m how to sort elements.
My question is that, since MyCompare::operator() is an ordinary member function(I mean, it’s not static or something else), we need an instance of MyCompare to call operator(), which means, to provide the address of the object.
But what is also clear that, there is no such thing in the code, and the code runs well.
Can anyone answer this for me? Thank you in advance.
>Solution :
A comparison function object in the map constructors is optional. You might want to pass it if a comparison type doesn’t have a default constructor.