2011-12-23 148 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慢。