基于x和y坐标排序

Avi*_*ash 2 c++ algorithm stl

我想vector根据xy坐标进行排序.以下就是我所做的,但我想要的是当我根据我排序时x,我得到了正确的,但当我进行排序时y,我不希望我的x订单应该改变.

#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 {
    bool operator ()(const item_t& left, const item_t& rigx) const {
        return left.x < rigx.x;
    }
};
struct compare_y {
    bool operator ()(const item_t& left, const item_t& rigx) const {
        return left.y < rigx.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::sort( items.begin(), items.end(), compare_x());
    std::copy(items.begin(),items.end(), std::ostream_iterator<item_t>(std::cout," ") );
    std::cout << std::endl;

    std::sort( items.begin(), items.end(), compare_y());
    std::copy(items.begin(),items.end(), std::ostream_iterator<item_t>(std::cout," ") );

    std::cout << std::endl;

}
Run Code Online (Sandbox Code Playgroud)

我想要的是给定一组点数顺序递增.即xy两者都增加.

Mat*_*Mat 6

你应该在一次通过中进行排序:

struct compare_xy {
    bool operator ()(const item_t& left, const item_t& right) const {
        return (left.x == right.x ? left.y < right.y : left.x < right.x);
    }
};
Run Code Online (Sandbox Code Playgroud)