-1

I am getting error while using map.

#include <bits/stdc++.h>

using namespace std;

class Vertex
{
  public:
    int x,y;
    Vertex(int x,int y) : x(x), y(y) {} 
}; 

class cmp {
  public:
    bool operator()(const Vertex &a, const Vertex &b)
    {
        return a.x < b.x;
    } 
}; 

int main() {   
    map<Vertex, Vertex, cmp> mp;
    Vertex u(0,0);
    Vertex v(1,2);
    mp[u] = v;//This line gives error
    return 0;
}

what is wrong with mp[u]=v?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Tijal
  • 11
  • 3
  • If you look at the error message (next time please add it to the question to save us time), you'll see that `[]` needs map elements to be default-constructible (because it default-constructs an element if it's missing). You could use something like `mp.emplace(u, v);`, **or** you could add a default constructor to `Vertex`. – HolyBlackCat Aug 06 '20 at 08:30
  • Also, instead of writing a custom comparator, you could overload `<` for your class (or specialize `std::less`, if you don't want people to call `<` on the class). Then you can write `map` and it will just work. Also please see [Why should I not #include ?](https://stackoverflow.com/q/31816095/2752075) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/2752075). – HolyBlackCat Aug 06 '20 at 08:32

1 Answers1

0

The line:

mp[u] = v;

Requires to construct an empty (default) Vertex and then assign v to it. The problem is that there is no default constructor of Vertex so the initial empty instance cannot be constructed.

There are two possible fixes:

First: Add a default constructor of Vertex:

class Vertex
{
public:
  int x, y;
  Vertex(int x, int y) : x(x), y(y) {}
  Vertex() : x(0), y(0) {}
};

Second: Use map::emplace instead of map::operator[] (my recommendation):

mp.emplace(u, v);

map::emplace constructs the whole pair of key and value at once without need to create a temporary "default" value of a map value.

And the next problem is your compare operator. It must be constant (comparator object must not be modified by each compare):

class cmp {
public:
  bool operator()(const Vertex &a, const Vertex &b) const
  {
    return a.x < b.x;
  }
};
Jarek C
  • 1,077
  • 6
  • 18