为什么main
中的最后一个圆不能打印所有 map ?
#include <map>
#include <iostream>
using namespace std;
class NAME
{
private:
string name;
public:
NAME(string name)
{
this->name = name;
}
string getName() const
{
return name;
}
friend bool operator< (const NAME& n1, const NAME& n2);
};
bool operator< (const NAME& n1, const NAME& n2)
{
return false;
// return n1.getName() < n2.getName();
}
int main()
{
map <NAME, int> telephoneBook = { {NAME("Alex"), 1122},
{NAME("Oleg"), 3344},
{NAME("Den"), 5566} };
for (auto it = telephoneBook.begin(); it != telephoneBook.end(); ++it)
{
cout << (it->first).getName(); // prints only Alex
}
}
输出:亚历克斯
最佳答案
map 中的两个元素在
!(a < b) && !(b < a)
由于您的operator<
始终返回false
,因此任何两个元素都被视为等效。请注意,您的
operator<
必须实现strict weak ordering。您的return n1.getName() < n2.getName();
做到这一点。
关于c++ - 迭代器不会在C++中打印所有 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64973089/