Make_heap和排序x和y坐标

make_heap and sorting x and y co-ordinates

本文关键字:坐标 排序 heap Make      更新时间:2023-10-16

我想获得最高坐标( x, y )以下是我写的代码,这是正确的代码吗?

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
struct item_t {
    int x;
    int y;
    item_t( int h, int w ) : x(h), y(w) {}
    friend std::ostream& operator<<(std::ostream& os, const item_t& gt) {
        os << "(" << gt.x << "," << gt.y << ")";
        return os;
    }
};
typedef std::vector<item_t> item_list_t;
typedef item_list_t::iterator item_list_itr_t;
struct compare_x_y {
    bool operator ()(const item_t& left, const item_t& right) const {
        return left.x < right.x && left.y < right.y;
    }
};

int main ( int argc, char **argv) { 
    item_list_t items;
    items.push_back(item_t(15, 176));
    items.push_back(item_t(65, 97));
    items.push_back(item_t(72, 43));
    items.push_back(item_t(102, 6));
    items.push_back(item_t(191, 189));
    items.push_back(item_t(90, 163));
    items.push_back(item_t(44, 168));
    items.push_back(item_t(39, 47));
    items.push_back(item_t(123, 37));
    std::make_heap (items.begin(),items.end(),compare_x_y());
    std::cout << "initial max heap   : " << "(" << items.front().x <<"," << items.front().y << ")" << std::endl;

}

是否对这个输入有效,而对其他输入无效

您的比较函数不是严格的弱排序,因此使用它将给出未定义的结果。

它不是严格弱排序,因为等价关系不是传递的。例如,(2,2)等于(4,1),(4,1)等于(3,3)。但是(2,2)不等于(3,3)(如果两个值都不小于另一个值,则认为是相等的)。

您需要提供另一个比较函数。一些例子:

  • 比较x,如果x值相等,则比较y。
  • 比较两点x+y