sort() a vector: quick question

J

John

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
 
I

Ivan Vecerina

John said:
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) );
}
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top