本文簡要介紹rust語言中 slice.binary_search_by_key
的用法。
用法
pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F) -> Result<usize, usize> where F: FnMut(&'a T) -> B, B: Ord,
Binary 使用鍵提取函數搜索這個排序的切片。
假設切片按鍵排序,例如 sort_by_key
使用相同的鍵提取函數。
如果找到該值,則返回 Result::Ok
,其中包含匹配元素的索引。如果有多個匹配項,則可以返回任何一個匹配項。該索引是確定性選擇的,但在未來的 Rust 版本中可能會發生變化。如果未找到該值,則返回 Result::Err
,其中包含可以插入匹配元素的索引,同時保持排序順序。
另請參見 binary_search
、 binary_search_by
和 partition_point
。
例子
在按第二個元素排序的對切片中查找一係列四個元素。第一個被發現,具有唯一確定的位置;沒有找到第二個和第三個;第四個可以匹配 [1, 4]
中的任何位置。
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
(1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
(1, 21), (2, 34), (4, 55)];
assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
相關用法
- Rust slice.binary_search_by用法及代碼示例
- Rust slice.binary_search用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust slice.iter_mut用法及代碼示例
- Rust slice.windows用法及代碼示例
- Rust slice.repeat用法及代碼示例
- Rust slice.group_by_mut用法及代碼示例
- Rust slice.align_to_mut用法及代碼示例
- Rust slice.as_chunks_unchecked用法及代碼示例
- Rust slice.fill用法及代碼示例
- Rust slice.array_windows用法及代碼示例
- Rust slice.sort_unstable_by用法及代碼示例
- Rust slice.sort用法及代碼示例
- Rust slice.rotate_left用法及代碼示例
- Rust slice.as_mut_ptr用法及代碼示例
- Rust slice.swap_unchecked用法及代碼示例
- Rust slice.get_unchecked用法及代碼示例
- Rust slice.split_array_mut用法及代碼示例
- Rust slice.contains用法及代碼示例
- Rust slice.splitn_mut用法及代碼示例
- Rust slice.split_first用法及代碼示例
- Rust slice.splitn用法及代碼示例
- Rust slice.is_sorted_by_key用法及代碼示例
- Rust slice.split_array_ref用法及代碼示例
- Rust slice.group_by用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 slice.binary_search_by_key。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。