-2

Why does the following code prints 1?

#include <iostream>
#include <map>
#include <string>
#include <utility>

struct Foo
{
  Foo(int bar, const std::string& baz)
    : bar(bar)
    , baz(baz)
  {}

  int bar;
  std::string baz;

  bool operator<(const Foo& rhs) const
  {
    if (bar < rhs.bar && baz < rhs.baz)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
};

int main()
{
    Foo first(0, "test");
    Foo second(1, "test");
    std::map<Foo, std::string> m;
    m.insert(std::make_pair(first, "test"));
    m.insert(std::make_pair(second, "test1"));
    std::cout << m.size() << std::endl;
}

The second call to insert says that we already have that item in the map. Why?

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

0

insert does nothing if the key is already present in the map.

0

The second call to insert says that we already have that item in the map. Why?

Because first is already in the map. That's exactly what a map is for: checking whether keys are in the map, and that's exactly what the error says.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94