i wanna sort the elements stored in a vector, but my sort function
needs be a little different from the standard one, i wanna the sort
function accept 3 parameters.
stl::sort(myvec.begin(), myvec.end(), mysortfunc);
bool mysortfunc(elem1, elem2, anoter parameter)
{
//is it possible ??
}
functor meets your requirement:
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
class comparer {// comparer is a funtor
public:
comparer(int c): c(c) {} // c is the third parameter.
template <class T>
bool operator ()(const T& a, const T& b) const { // you can use the
third parameter here
cout << "comparing " << a << " and " << b << " using parameter: " <<
c << endl;
return a < b;
}
private:
int c; // the variable hold the third parameter.
};
int main(int argc, char* argv[])
{
vector<intv;
for(int i=1; i<10; i++)
{
v.push_back(i * i % 13);
}
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
sort(v.begin(), v.end(), comparer(5));
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
return 0;
}