Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can I use a class as custom comparison criterion as a template argument to std::map without providing a class instance

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading