quick question: sort() a vector

J

John

I would like to sort a vector using a comparison function of
my own, the problem is that the comparison function is dependent
on the first element of the vector. I do not want to make this
element global. Ideally I would like to send the compare function
three elements instead of two?

Any other ways to cleanly do this?

Thanks a lot,
--j
 
W

Wiseguy

John said:
I would like to sort a vector using a comparison function of
my own, the problem is that the comparison function is dependent
on the first element of the vector. I do not want to make this
element global. Ideally I would like to send the compare function
three elements instead of two?

I haven't tried this but maybe derive a new class from std::vector
and overload the less() method in the derived class, providing some
default behavior for an empty vector?

IIRC less() is used in ordered containers and in std algorithms when
sorting is required.
 
R

Rolf Magnus

John said:
I would like to sort a vector using a comparison function of
my own, the problem is that the comparison function is dependent
on the first element of the vector. I do not want to make this
element global. Ideally I would like to send the compare function
three elements instead of two?

Any other ways to cleanly do this?

Make it a function object (which is potentially more efficient anyway):

struct my_comparison
{
my_comparison(int the_value)
: value_(the_value)
{
}

bool operator()(int lhs, int rhs)
{
//do the comparison, dependent on value_
}

int value_;
}


vector<int> vect;
//...
std::sort(vec.begin(), vec.end(), my_comparison(vec.front()));
 
R

Richard Herring

John said:
Thanks a lot, this seems to work.

Just be careful that your three-argument "comparison" still obeys the
rules for a strict weak ordering. If it doesn't, you will get undefined
behaviour.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top