c++ - 迭代器不会在C++中打印所有 map

标签 c++ dictionary

为什么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/

相关文章:

c++ - C/C++ 中某些头文件中的 sys/type.h

c++ - 为什么我的计算机中 long int 和 int 具有相同的最大值

c++ - 使用父窗口在对象中启动线程

python - 我想将字典键从字符串更改为整数

python - 从键中减去字典值

python - 在 python 中增长字典是否有有效的替代方法?

python - 如何使用 dict 值列表将字典列表转换为 dict

python - 我如何使用字典理解来计算文档中每个单词的出现次数

c++ - 链接 INTEL tbb 库时遇到问题

c++ - 如何强制INTERFACE库上的依赖项使用C++ 11或更高版本?