能否在std::partition的条件判断中使用两个return语句?
Absolutely, you can have multiple return statements in a lambda passed to std::partition—but here's the catch: once the first return executes, the lambda exits immediately. That's exactly why your second return statement never runs. It's not a syntax error, but it's not serving the "either condition is true" logic you need for your segment grouping.
Let's break down your use case: you want to group segments where either one endpoint of segment 1 is close enough to segment 2, or the other endpoint meets the distance threshold. This is a classic logical OR scenario, not two separate early-exit paths.
Fixing your code
Instead of returning early for each condition, combine them into a single boolean check using || (logical OR). Here's a concrete example tailored to your scenario:
// Assume you have a helper function to calculate distance between a point and segment double point_to_segment_distance(const Point& p, const Segment& seg); // Define your distance threshold (adjust based on your needs) const double threshold = 1.0; std::partition(segments.begin(), segments.end(), [target_segment](const Segment& s) { // Calculate both distances first (optional, but makes logic clearer) double dist_start = point_to_segment_distance(s.start, target_segment); double dist_end = point_to_segment_distance(s.end, target_segment); // Return true if EITHER distance is below the threshold return dist_start < threshold || dist_end < threshold; });
Why your original approach failed
If you wrote something like this (with consecutive returns), the second line is unreachable:
// ❌ This won't work as intended std::partition(..., [](const Segment& s) { return point_to_segment_distance(s.start, target) < threshold; return point_to_segment_distance(s.end, target) < threshold; // Never runs });
The first return exits the lambda immediately, so the second condition is never checked. If you used conditional branching (like an if/else), that would work for OR logic—but using || is more concise and readable for this case.
Bonus: Optimizing for performance
If calculating the distance is expensive, you can take advantage of short-circuit evaluation with ||: the second distance won't be calculated if the first one already meets the threshold. That's a nice free optimization!
内容的提问来源于stack exchange,提问作者Grillteller

