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

sort() a vector: quick question

P: n/a


I want to sort a vector and am implementing a comparison
function, say my_comparison. I would like to send the comparison
function a third argument which changes from time to time.
I understand I can do this using a global variable for the
third variable. Any other suggestions on how to accomplish this?

Thanks,
--j

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


P: n/a
"John" <we**********@yahoo.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
I want to sort a vector and am implementing a comparison
function, say my_comparison. I would like to send the comparison
function a third argument which changes from time to time.
I understand I can do this using a global variable for the
third variable. Any other suggestions on how to accomplish this?


Use a predicate class.

Here's a trivial example you should be able to adapt easily:

class MyCompare
{
bool inverse_; // use any data members you need
public:
MyCompare(bool inverse)
: inverse_(inverse) {}

bool operator( std::string const& a, std::string const& b )
{
if( inverse_ ) return b<a;
else return a<b;
}
};

void mySort( std::vector<std::string>& v, bool inverse )
{
std::sort( v.begin(), v.end(), MyCompare(inverse) );
}
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.