1

Why last cicle in main doesn't print all 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
    }
}

Output: Alex

Denis_newbie
  • 1,128
  • 4
  • 13
  • 5
    Why are you doing `return false;` in `bool operator< (const NAME& n1, const NAME& n2)` instead of `return n1.getName() < n2.getName();`? – NathanOliver Nov 23 '20 at 17:17
  • 1
    Since this is not your first question on this code example, I suppose you may need a somewhat better learning source. May I suggest [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of what you have now? – Yksisarvinen Nov 23 '20 at 17:23

1 Answers1

2

Two elements in the map are considered equivalent when

!(a < b) && !(b < a)

As your operator< returns false always, any two elements are considered equivalent.

Note that your operator< must implement a strict weak ordering. Your

return n1.getName() < n2.getName();

does that.

463035818_is_not_a_number
  • 88,680
  • 9
  • 76
  • 150