为什么我们必须重载'<'运算符以使用is_permutation并包含算法

时间:2019-05-04 10:16:05

标签: c++ algorithm stl

我有一个向量,该向量持有点的向量,这是一个具有x和y坐标的类。我基本上必须从向量中删除所有排列和子集。为此,我利用算法包括了is_permutation

我已经重载了'=='运算符,为什么我们需要它是有道理的。但是除非我重载'<'运算符,否则这两种算法将不起作用。

这是我的重点课:

class Point{

private:    
    int x;
    int y;
public:
    Point(){
        x=0;
        y=0;
    }
    Point(int xx, int yy){
        x=xx;
        y=yy;
    }

    double getSlope(Point p){
        if(this->x!=p.x && this->y!=p.y){
            return (double)(double(this->y-p.y)/double(this->x-p.x));
        }else if(this->x==p.x){
            return INT_MAX;
        }else{
            return INT_MIN;
        }
    }   
    void print(){
        cout<<"(" <<x<<","<<y<<")";
    }
    bool operator == (Point &p){
    if(this->x==p.x && this->y==p.y )
        return true;
    else
        return false;
    }
    bool operator < (Point &p){
        cout<<"\nin the < operator\n";
    if(this->x < p.x && this->y < p.y )
        return true;
    else
        return false;
    }
};

这是接受点临时矢量的函数 并将其与vector>进行比较以删除排列。 这些点是从文件中获取的,因此,当我们获得这些点时,我们只会在通过检查的情况下将其添加到vector>中

bool check(PointVector temp, vector<PointVector> pointArrays ){

    for(int i =0 ; i < pointArrays.size(); i++){
        if(is_permutation(pointArrays[i].begin(),pointArrays[i].end(),temp.begin())){
            return false;
        }else if(includes(pointArrays[i].begin(),pointArrays[i].end(),temp.begin(),temp.end())){
            return false;
        }else if(includes(temp.begin(),temp.end(),pointArrays[i].begin(),pointArrays[i].end())){
            pointArrays[i].swap(temp);
            return false;
        }

    }
    return true;
}

Point Vector是vector<points>;

的typedef

1 个答案:

答案 0 :(得分:5)

这大约是std::includes,这对要排序的输入序列(根据比较器-operator<)有要求。

在此前提下,可以使用operator==(语义不是(<>)和相同的线性渐进复杂度来实现该算法。如果没有排序的要求(以及第一个范围的随机访问迭代器),它将是O(n log m)。

但是使用operator<,我们可以更快地决定是否应该从算法中返回false,因为我们已经从第二个序列中读取了一个元素,该元素位于第一个序列中的下一个元素之前

简而言之,处理有序序列的算法在有序比较器方面起作用。