2

I want to find the minimum of a vector:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main () {
    vector<double> v{2, 0, 4};
    double minT = *std::min_element(v.begin(), v.end(),
                                    [](double i1, double i2) {
                                        std::cout << "Comparing: " << i1 << "  " << i2 << "   " << ((i1 < i2)? i1:i2) << "    " << '\n';
                                        return (i1 < i2)? i1:i2;
                                    });
    cout << "Minimum is: " << minT << '\n';
}

But the output of this piece of code is:

Comparing: 0  2   0    
Comparing: 4  2   2    
Minimum is: 4

What am I doing wrong? Is there any undefined behaviour there?

NOTE: I know I do not need the lambda function. Removing it returns the expected result (0), but my goal is to have a personalized min function which does not consider zeros.

10
  • Worth pointing out that your function is not stable. That is, if two elements are equal, you probably want to get the first; your code will get the second. You might want to consider !(i2<i1). (Not a requirement though) Commented Mar 9, 2015 at 16:38
  • @BoBTFish thanks for the note, but I do not see how that makes it not stable. Could you give an example please? In may case, since I only want the value I do not really care about position, but just in case. Commented Mar 9, 2015 at 16:40
  • "Stable" is a bad word, since it really refers to sorting, in that a stable sort keeps equal elements in their original order. But say your container has {1, 1, 1}. Your min_element (once fixed) returns an iterator to the last 1, when most people would probably expect the first. Commented Mar 9, 2015 at 16:42
  • 1
    An epsilon is usually used when wanting to consider close values as equal. Not sure it makes sense for ordering. That's a genuine "not sure" - I really don't know what you should do here. Suggest making a new question with more detail. Search first of course, might be answered already. Commented Mar 9, 2015 at 16:55
  • 1
    epsilon-comparisons do not provide a strict weak ordering and hence are not valid comparators for standard algorithms. Commented Mar 9, 2015 at 17:30

1 Answer 1

16

The comparator needs to return true if the first argument is less than the second, not the smaller of the two values. So the return statement should just be

return i1 < i2;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.