0

I have the following code, which tries to find an element from myPairs, which is a std::vector of MyPair. The code works fine, but I feel it could be more elegant. Can anyone please advice, thanks.

std::optional<MyPair>
find_right_data(const MyPairs &my_pairs, const MyPoint &pos) {

    MyPair pair;
    bool found = false;

    double min_dist = std::numeric_limits<double>::max();
    for (size_t i = 0; i < my_pairs.size(); i++) {

        MyLine myline = my_pairs[i].second;
        double dist = std::numeric_limits<double>::max();
        find_closest_point(myline, pos, &dist);

        if (dist < min_dist) {
            min_dist = dist;
            pair = my_pairs[i];
            found = true;
        }

    }

    if (found) {
        return pair;
    } else {
        return {};
    }
}
Edamame
  • 23,718
  • 73
  • 186
  • 320
  • So you are using `std::optional` outside but inside you want to simulate that using boolean flag? Strange – Slava Feb 26 '19 at 19:22
  • If you want help improving work code you should post this on [CodeReview.SE](https://codereview.stackexchange.com/help/how-to-ask). If you do decide to do so please delete the question here. – NathanOliver Feb 26 '19 at 19:23
  • This looks like a job for [std::min_element](https://en.cppreference.com/w/cpp/algorithm/min_element) with a custom comparator. – Igor G Feb 26 '19 at 22:25

0 Answers0