1

Hello to everyone who will find this post helpful. I had this custom class Position and I wanted to use it in std::map

class Position
{
public:
    int x;
    int y;

    Position(const int &pos_x, const int &pos_y)
        : x(pos_x), y(pos_y) {}
};

But i had error because it couldn't compare the classes to each other. So I created this comparison class:

class PosComparator
{
public:
    bool operator()(const ConsoleRenderer::Position &A, const ConsoleRenderer::Position &B)
    {
        if (A.x < B.x)
            return true;
        else if (A.x == B.x && A.y < B.y)
            return true;
        return false;
     }
};

But I got this this error:

static assertion failed: comparison object must be invocable as const

2 Answers2

1

As the error implied, adding const at the end solves the problem:

class PosComparator
{
public:
    bool operator()(const ConsoleRenderer::Position &A, const ConsoleRenderer::Position &B) const
    {
        if (A.x < B.x)
            return true;
        else if (A.x == B.x && A.y < B.y)
            return true;
        return false;
    }
};

Or make it shorter by using std::tie, creating tuples which can be use to compare:

class PosComparator
{
public:
    bool operator()(const ConsoleRenderer::Position &A, const ConsoleRenderer::Position &B) const
    {
        return std::tie(A.x, A.y) < std::tie(B.x, B.y);
    }
};
silverfox
  • 1,568
  • 10
  • 27
0

I solved it with simply adding const at the end of the line.

class PosComparator
{
public:
    bool operator()(const ConsoleRenderer::Position &A, const ConsoleRenderer::Position &B) const
    {
        if (A.x < B.x)
            return true;
        else if (A.x == B.x && A.y < B.y)
            return true;
        return false;
     }
};

Hopefully this helped. :)