简体   繁体   English

在结构中为另一个结构的2个对象定义运算符<

[英]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. 我在C ++中有一个小问题,希望您能为我提供帮助。

I want to define a struct myPoint. 我想定义一个结构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. 我希望myPoint的每个“实例”都能够自己比较两个点。 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. 因此,每个myPoint在比较两个点x,y时都应考虑自己的点p。 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. 从语法上讲,仅使该操作符具有一个点似乎是可能的,我想它会将一个点与myPoint进行比较,但这不是应该的。 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. 问题的背景是,我想使用预定义的排序函数对点向量进行排序,并希望将myPoint对象作为排序“函数”。

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。

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. 不过,我有疑问,假设ccw表示逆时针方向,我认为这不是有效的排序条件。

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 正如@KonradRudolph所指出的,重载<在这种情况下是没有意义的,因为您无法在排序或其他任何操作中使用它

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. 使用常量引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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