By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,148 Members | 1,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,148 IT Pros & Developers. It's quick & easy.

quick question: sort() a vector

P: n/a

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

Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"John" <we**********@yahoo.com> scribbled on the stall wall:

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.

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Jul 23 '05 #2

P: n/a
John wrote:

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()));
Jul 23 '05 #3

P: n/a
Thanks a lot, this seems to work.

Jul 23 '05 #4

P: n/a
In message <11**********************@o13g2000cwo.googlegroups .com>, John
<we**********@yahoo.com> writes
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.

--
Richard Herring
Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.