简体   繁体   中英

Define Operator < in struct for 2 objects of another struct

I have a little problem in C++ and i hope you are able to help me out.

I want to define a struct myPoint. This struct should be able to compare two objects from type point (defined as pair). I want every "Instance" of myPoint to be able to compare two points on its own. This is what i tried to code:

typedef pair<int,int> point;
struct myPoint{
    point p;
    inline bool operator<( point x, point y ){
    return !ccw(p,x,y);
}

So every myPoint should consider his own point p while comparing two points x,y. The (translated) Error I get is

"error C2804:  Binary Operator '<' has too much Arguments/Parameters"

It seems like it's syntacticly possible to make this operator with only one point, I guess the it would compare a point to a myPoint, but that's not what it should be. Background of the problem is that i want to use a predefined sort function to sort a vector of points and as sorting "function" I want to deliver a myPoint object.

I think (maybe) that what you are trying to do is write a functor

struct myPoint
{
    myPoint(point p) { this->p = p; }
    bool operator()(point x, point y) const
    {
        return !ccw(p,x,y);
    }
    point p;
};

A functor can be passed as the third argument to std::sort.

std::sort(vec.begin(), vec.end(), myPoint(p));

I have my doubts though, assuming ccw means counterclockwise I don't think this is a valid sort condition.

The < defines overload with only one parameter. As noted by @KonradRudolph, it makes no sense to overload < in this case 'cause you couldn't use it in sorting or anything

typedef pair<int,int> point;
struct myPoint{
    point p;
    bool smaller(const point &a, const point &b)
    {
        return !ccw(p,a,a)
    }
};

This fragment should illustrate basic things for you:

#include <utility>

typedef std::pair<int,int> point;

bool less(const point& p1, const point& p2)
{
    return (p1.first < p2.first) ||
           ((p1.first == p2.first) && (p1.second == p2.second));
}

struct myPoint {
    point p;
    inline bool operator < (const point& p2) {
        return less(p, p2);
    }
};

int main()
{
    return 0;
}
  1. You had not 'closed' operator <.
  2. Operator < requires exactly one argument if is a method like here.
  3. Use constant references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM