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

std::map::find does not access operator==

I created a class MyString and overloaded operator==.
MyString can be used without any problems

class MyString
{
public:
    bool operator== (const MyString& obj) const;
};

I want to use MyString as key in std::map.

std::map<MyString, value> m_xxx;

I can access the inserted data by iterating.

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

for (auto& it : m_ini)
{
    MyString first = it.first;
    for (auto& sit : it.second)
    {
        MyString key = sit.first;
        MyString value = sit.second; 
        int i = 0;
    }
}

But when using std::map::find the data I inserted cannot be searched

auto& it = m_ini.find(section);
if (it == m_ini.end())

I take for granted that std::map::find will do the comparison through my operator==.But in VS debugger std::map::find single step doesn’t break down at my operator== .
I don’t know where the problem is, can anyone help me!

>Solution :

std::map does not use operator==. It is a sorted container and by default operator< is used to compare keys of elements in the map.

std::map has 4 template arguments:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map

The third one can be used to select a different comparator. std::less<Key> uses the keys operator<.

Actually a std::map does not care about equality. Two keys a and b are considered equivalent when !(a<b) && !(b<a). Keys are not required to have an operator==.

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