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.
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!
CodePudding user response:
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==
.