You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia新手咨询:如何用searchsortedfirst查找指定y字段的Record元素

How to Use 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 by parameter tells searchsortedfirst which part of your Record to use for comparison. In your case, we care about the y field, so we'll pass a function that extracts y from each Record.
  • The default lt (less-than) comparator (isless) works perfectly for integer values like your y::Int64, since it follows the standard numeric ordering that searchsortedfirst expects.

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?

  1. The by=r -> r.y argument tells searchsortedfirst to ignore the value field and only compare the y values of your Records.
  2. searchsortedfirst returns the first index where the y value is greater than or equal to target_y. Since your array is sorted, if a Record with y == target_y exists, this will be its index (or the first occurrence if there are duplicates).
  3. We add the check A[idx].y == target_y to handle edge cases: when target_y is larger than all y values in the array (which would make idx = length(A)+1, out of bounds) or when the first ">= element" is actually larger than target_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:00:48