2013-02-07 35 views
2

我正試圖編寫一個函數來按照各種不同的屬性對自定義類對象的向量進行排序。按C++中的參數進行排序?

C++的排序的參考,在這裏找到:

http://www.cplusplus.com/reference/algorithm/sort/

說,你可以排序是這樣的:

std::sort (myvector.begin(), myvector.end(), myfunction); 

我想做什麼就能做的是傳遞一個參數我的功能,除了從我的載體這樣兩個對象是這樣的:

std::sort (myvector.begin(), myvector.end(), myfunction(mode=7)); 

你知道這樣做嗎?

我對C++比較陌生,來自python,這很容易。

+1

如何你使用'mode'嗎? – billz

+0

更正,在這裏找到['std :: sort()'參考](http://en.cppreference.com/w/cpp/algorithm/sort):http://en.cppreference.com/w/ cpp/algorithm/sort – Johnsyweb

+0

'mode = 7'是什麼意思?你將如何在[tag:python]中實現這一點? – Johnsyweb

回答

3

您可以使用仿函數,而不是一個自由的功能:

struct Functor{ 
    int mode; 
    bool operator() (int a,int b) { return (a<b);} 
} functor; 

重載()運算符在sort調用函子時執行。在那裏你可以有一個變量mode並根據需要使用它。 然後設置模式(你也可以設置在仿函數的構造函數),並調用sort使用它:

functor.mode = 7; // or set it in the constructor 
std::sort (myvector.begin(), myvector.end(), functor); 
+1

酷!我不知道函數。他們似乎很有用。 –

1

創建一個仿函數:

struct MyFunction { 
    bool operator()(const T& lhs, const T& rhs) const { /* implement logic here */ } 
    int mode; 
}; 

然後代替你傳遞平原功能myfunction的那一個實例。在這裏,T是用於實例化您的std::vector的類型。

MyFunction f; 
f.mode = 7; 
std::sort (myvector.begin(), myvector.end(), f); 

如果你有C++ 11的支持,你可以使用lambda函數:

std::sort(myvector.begin(), myvector.end(), [](const T&a, const T& b) { /* implement*/ }); 
5

如果您正在使用C++ 11,你可以使用lambda:

sort(myvec.begin(), myvec.end(), [] (Type a, Type b) { return myfunction(a,b,7); }); 
+1

如果你不使用C++ 11,'boost :: bind'基本上與'std :: bind'兼容。 –