0

I want to create a method inside a class (but I think this is irrelevant) that sorts a vector according to the bool value returned by a particular function... I read that it is possible but I don't know how to do it...

I would like to call the function and put (for example) >, or <, as a parameter, so that I don't have to create two almost identical functions.

How I imagine the body of the function:

for (int i = 0 ; i < DIM - j; i++) { if (some_function(v[i], v[i+1])) { int temp; temp = v[i]; v[i] = v[i+1]; v[i+1] = temp; } } 
4
  • 1
    std::sort() takes a user-definable comparator Commented Jul 10, 2020 at 14:34
  • 1
    @AdrianMole: There are other techniques for C++. E.g. functors, std::function, lambdas. Commented Jul 10, 2020 at 14:34
  • 1
    The C dupe is a poor choice, especially if this is an X/Y question (i.e. reinventing the wheel). Commented Jul 10, 2020 at 14:36
  • @underscore_d I looked for a C++ dupe, but that just pointed to the C version: stackoverflow.com/q/6339970/10871073 Commented Jul 10, 2020 at 14:37

1 Answer 1

0

You can do this by passing in a function object:

template <typename Op> void f(Op op) { // ... if (op(v[i], v[i+1])) // ... } 

and call it like this:

f(std::less{}); // for < f(std::greater{}); // for > 

Of course, f here is just an example, but you just need to add a template parameter to your own function in this way.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.