468,746 Members | 1,944 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,746 developers. It's quick & easy.

how to use stl sort in this case

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 ??
}

Nov 20 '06 #1
2 1494
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;
}

Nov 20 '06 #2

thinktwice wrote:
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 ??
}
#include <boost/bind.hpp>

stl::sort(myvec.begin(), myvec.end(), boost::bind(&mysortfunc. _1, _2,
another_parameter));

Nov 20 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by its me | last post: by
40 posts views Thread by Elijah Bailey | last post: by
1 post views Thread by Aravind | last post: by
reply views Thread by thomasp | last post: by
48 posts views Thread by Alex Chudnovsky | last post: by
3 posts views Thread by usaccess | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.