2012-10-07 22 views
0

我需要知道我們如何可以排序的用戶向量使用它的元素定義類的向量。 假設我有一個名爲「座標」的類,getX和getY方法返回一個int值。 我已經創建了矢量「vector PointTwoD vcP2D(5);」排序使用它的元素

class coordinates { 
int getX(); 
int getY(); 

) 

現在問題, 1)I需要排序使用的getX的載體「vcP2D」()和排序在遞增順序 2)假設一個用戶輸入了「2」作爲x座標。並使用該信息我需要找到其載體包含2

請指點

回答

6

這將做:

std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d){ return c.getX() < d.getX(); }); 

它使用C++ 11 Lambda表達式作爲std::sort二進制謂詞。

demonstration

#include <algorithm> 
#include <vector> 

#include <iostream> 

struct coordinates 
{ 
    int x; 
    int y; 
}; 

int main() 
{ 
    std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} }; 

    std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.x < d.x; }); 

    std::cout << "sorted by x values, values of \"x\": " << v[0].x << " " << v[1].x << " " << v[2].x << "\n"; 

    std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.y < d.y; }); 

    std::cout << "sorted by y values, values of \"x\": " << v[0].x << " " << v[1].x << " " << v[2].x << "\n"; 
} 

以同樣的方式demo of how to find an element

#include <algorithm> 
#include <vector> 

#include <iostream> 

struct coordinates 
{ 
    int x; 
    int y; 
}; 

int main() 
{ 
    std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} }; 

    auto result = std::find_if(v.begin(), v.end(), [](const coordinates& c){ return c.x == 1 && c.y == 5; }); 
    if(result != v.end()) 
    std::cout << "point (1,5) is number " << std::distance(v.begin(), result)+1 << " in the vector.\n"; 
    else 
    std::cout << "point (1,5) not found.\n"; 
} 

如果您正在尋找在排序向量進行搜索,您可以使用std::binary_search,這需要比較功能(與上面的std::sort相同)。它也沒有給一個迭代該元素,只有truefalse

+0

發現的示範也不錯。不知道是否搜索排序或未排序的數據是OP想要的。 –

+0

@LucDanton完成。他可以找到自己的'的std :: binary_search'代碼我想':)' – rubenvb

+0

我推薦「LOWER_BOUND」過度「binary_search」。 'binary_search'很少有幫助,我不認爲它應該在STL中。 –

3

你需要在你的元素定義了嚴格的弱勢整理,或者使用operator<()或二元謂詞,然後用std::sort()

最簡單的方法是創建一個小於operator<()

bool operator< (coordinates const& c0, coordinates const& c1) { 
    // return a suitable result of comparing c0 and c1 such that operator<() 
    // become a strict weak order 
} 

有了這一切,你需要做的排序std::vector<coordinates>是使用std::sort()。要找到一個特定的對象,您可以使用std::lower_bound()

+0

@KenBloom對不起,我不明白。我是新來的載體和C++請指教更清楚 – rasul1719435

+0

我仍然不得到它,你能解釋一下我們的一些運行代碼。我仍然在學習如何使用矢量和東西。仍然是一名學生,所以我不喜歡只對流 – rasul1719435