2011-12-23 209 views
2

我想根据xy坐标对vector进行排序。以下是我所做的,但我想要的是当我根据x排序,我得到适当的,但是当我根据y进行排序时,我不希望我的x顺序应该改变。基于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 { 
    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; 

} 

我想给出一组点顺序的升序。即xy都在增加。

+0

你能给出一个你期望的输出的例子吗?这个问题不是很清楚。 – Naveen 2011-12-23 08:14:50

+0

首先,您必须决定当'left.x rigx.y'时你期望什么。在这种情况下,它们应该是什么顺序? – Skyler 2011-12-23 08:16:59

回答

5

你应该做在单次排序:

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); 
    } 
}; 
+0

如果这就是他正在寻找的(而不是'std :: stable_sort')。然而,在这种情况下,为了尊重他的描述和例子中的顺序,你应该首先比较'y',而不是'x'。 – 2011-12-23 09:07:53

+0

我放的东西与我对这个问题的理解相匹配 - 先按X排序,再按X排序,按Y排序。 – Mat 2011-12-23 09:11:50

+0

确定他想从问题中得到什么是相当困难的。我把它解释为先按X排序,然后按Y排序,但当Y相等时不要扰乱顺序。事实上,他似乎要求我的是稳定的排序。但我承认他的问题可以用很多方式来解释。 – 2011-12-23 10:06:19

4

你必须只创建一个比较,只有一个呼叫std::sort

struct compare_xy { 
    bool operator()(const item_t& left, const item_t& right) const { 
     return (left.x < right.x) || ((left.x == right.x) && (left.y < right.y)); 
    } 
}; 
1

这并不完全清楚,我是你“问。如果你的目标是 排序y,与x确定何时y的是平等的顺序, 然后一个调用排序与比较功能:

struct OrderYThenX 
{ 
    bool operator()(item_t const& lhs, item_t const& rhs) const 
    { 
     return lhs.y < rhs.y 
      || (!(rhs.y < lhs.y) && lhs.x < rhs.x); 
    } 
}; 

这将导致items具有相同订单,因为它终于在你的代码 。

如果象似乎从你的描述,你的 例如部分更可能的是,你要平等y的S对象之间的顺序是 不变,当你按y,不管如何的值 有序相对于到x,你应该使用std::stable_sort。只是 知道它可能比std::sort慢。