2013-02-07 37 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'兼容。 –