Julia新手咨询:如何用searchsortedfirst查找指定y字段的Record元素
searchsortedfirst with Custom Record Type in Julia Hey there! Since you're new to Julia, let's walk through how to solve this problem clearly and simply.
First, let's recap your goal: you have a sorted array of Record objects, and you want to use searchsortedfirst to find the index of the first Record where the y field equals a given x.
Do you need by, lt, or both?
You only need the by transformation function here—no need to define a custom lt comparator. Here's why:
- The
byparameter tellssearchsortedfirstwhich part of yourRecordto use for comparison. In your case, we care about theyfield, so we'll pass a function that extractsyfrom eachRecord. - The default
lt(less-than) comparator (isless) works perfectly for integer values like youry::Int64, since it follows the standard numeric ordering thatsearchsortedfirstexpects.
Example Code
Let's put this into practice. Note that in Julia 1.0+, we use struct instead of the old type keyword (I'll adjust that for you to follow modern syntax):
# Define your Record type (modern Julia syntax) struct Record y::Int64 value::Float64 end # Create a sorted array of Records (make sure it's sorted by y!) A = [Record(1, 0.5), Record(3, 1.2), Record(5, 2.0), Record(7, 3.1)] # The x value we want to match against the y field target_y = 3 # Call searchsortedfirst with the by parameter idx = searchsortedfirst(A, target_y, by=r -> r.y) # Verify we found a matching element (since searchsortedfirst returns the first >= target) if idx <= length(A) && A[idx].y == target_y println("Found matching Record at index $idx: $(A[idx])") else println("No Record with y = $target_y exists in the array") end
What's happening here?
- The
by=r -> r.yargument tellssearchsortedfirstto ignore thevaluefield and only compare theyvalues of yourRecords. searchsortedfirstreturns the first index where theyvalue is greater than or equal totarget_y. Since your array is sorted, if aRecordwithy == target_yexists, this will be its index (or the first occurrence if there are duplicates).- We add the check
A[idx].y == target_yto handle edge cases: whentarget_yis larger than allyvalues in the array (which would makeidx = length(A)+1, out of bounds) or when the first ">= element" is actually larger thantarget_y.
If your array was sorted in descending order of y, you'd just add rev=true to the call:
idx = searchsortedfirst(A, target_y, by=r -> r.y, rev=true)
That's all you need! No custom lt function required here—keep it simple with the by parameter.
内容的提问来源于stack exchange,提问作者 J.Kennsy

