3

I need a std::set<std::pair<int,NodeA>>. So i need to overload the < operator of NodeA. I did it, but it doesn't work.

void matriceLab::aStar(int* matX,const int x, const int y, const int endX,const int endY){
    std::set<std::pair<int,NodeA>> nodi;
    allocaNodi(nodi,matX,x,y,endX,endY);


}
void matriceLab::allocaNodi(std::set<std::pair<int,NodeA>>& nodi, int* matX,const int x, const int y,const int endX,const int endY){
    for(int i = 0; i < x; i++){
        for(int j = 0; j < y; j = j + 2){
            NodeA nodo(i,j,endX,endY);
            std::pair <int,NodeA> pair1(i + j * x, nodo);
            nodi.insert(pair1);
        }
    }
}

class NodeA
{
//...
       bool operator<(const NodeA& a){
            if(posX < a.posX){
                return true;
            }else{
                return false;
            }
        }
//...
}

C:\TDM-GCC-32\lib\gcc\mingw32\5.1.0\include\c++\bits\stl_pair.h|222|error: no match for 'operator<' (operand types are 'const NodeA' and 'const NodeA')|

C:\Users\cristina\Desktop\università pdf\Laboratorio di Programmazione\progetti c++_SFML_openGL\SFML-2019-4-Grid\NodeA.h|24|note: candidate: bool NodeA::operator<(const NodeA&) << near match>>

vrige
  • 297
  • 1
  • 9
  • 7
    `bool operator<(const NodeA& a) {` -> `bool operator<(const NodeA& a) const {`? – Algirdas Preidžius Oct 30 '19 at 13:52
  • 2
    [Tangent] If you use `if(condition) return true; else return false;` just use `return condition;` instead. – NathanOliver Oct 30 '19 at 13:53
  • *Why* do you need this set? What is is to be used for? What is the actual problem you need to solve? Perhaps there are better solutions? – Some programmer dude Oct 30 '19 at 13:53
  • The type you are using for `std::set` and the way you insert into it makes it seem as if you really want a `std::map` or `std::vector`. You have not shown how it is used, though, so I cannot be sure. – walnut Oct 30 '19 at 13:55
  • Does your `operator<` need to modify the object? If not, is your `operator<` marked as `const`? – Eljay Oct 30 '19 at 13:59

1 Answers1

2

Reference: https://en.cppreference.com/w/cpp/language/operator_comparison

This reference says that as a member function, operator< has the format:

bool T::operator <(const T2 &b) const;

You need to mark your operator definition const since C++ wants you to promise that a mere < operator will not change the object(s) involved and will work with instances of the class that are declared const.

So you are missing the keyword const in the operator's overloading function. You will have to write:

bool operator<(const NodeA& a) const{
        if(posX < a.posX){ ...

If you are interested in knowing where exactly does c++'s code mention this, you can take a look at this StackOverFlow answer: https://stackoverflow.com/a/23927045/7865858

MrProgrammer
  • 443
  • 3
  • 13