Domanda

I stumbled upon a problem I cannot solve regarding maps. As we know, maps require the two type of variables it is gonna handle i.e. map, but what about custom types?

Let's say I have an object called 'Point' which consists in two variables, x and y. Is it feasible to declare a map like: map?. Please look at the code below

class Point
{
public:
double x;
double y;
Point(double x, double y)
{
    this->x=x;
    this->y=y;
}
};

int main(int argc, const char * argv[])
{
      map<Point,int> myMap;
      Point p1(0,0);
      myMap[p1]=1;
} 

I'm receiving a compilation error: 'Invalid operands to binary expression ('const Point' and 'const Point').

Does anyone know why this is happening and how can I solve it? Any help would be really appreciated :).

Cheers!

È stato utile?

Soluzione

You need to provide operator< for Point. std::map internally calls operator< to sort key.

bool operator<(const Point& lhs, const Point& rhs) 
{
    // compares lhs.x to rhs.x,
    // then lhs.y to rhs.y
    return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}

see map, it takes Compare function from template parameter, std::less<key> is default value.

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top