2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

BTreeSetとBTreeMapで最小値・最大値を取得する

Last updated at Posted at 2024-04-27

BTreeSetとBTreeMapで最小値・最大値を取得する方法を紹介します。

BTreeSet

まず、firstlastを利用する方法があります。

let mut set = BTreeSet::new();
set.insert(2);
set.insert(3);
set.insert(1);
set.insert(5);
set.insert(4);

if let Some(min) = set.first() {
    println!("min={}", min); // min=1
}
if let Some(max) = set.last() {
    println!("max={}", max); // max=5
}

iterを利用することも可能です。

let mut set = BTreeSet::new();
set.insert(2);
set.insert(3);
set.insert(1);
set.insert(5);
set.insert(4);

if let Some(min) = set.iter().next() {
    println!("min={}", min); // min=1
}
if let Some(max) = set.iter().next_back() {
    println!("max={}", max); // max=5
}   

BTreeMap

BTreeSetfirstlastに対応するものとして、first_key_valuelast_key_valueがそれぞれあります。

let mut map = BTreeMap::new();
map.insert("C", 3);
map.insert("B", 2);
map.insert("E", 5);
map.insert("A", 1);
map.insert("D", 4);

if let Some((min_key, min_value)) = map.first_key_value() {
    println!("min_key={} min_value={}", min_key, min_value); //=> min_key=A min_value=1
}
if let Some((max_key, max_value)) = map.last_key_value() {
    println!("max_key={} max_value={}", max_key, max_value); //=> max_key=E max_value=5
}

BTreeSetと同じくiterを利用しても取得可能です。

let mut map = BTreeMap::new();
map.insert("C", 3);
map.insert("B", 2);
map.insert("E", 5);
map.insert("A", 1);
map.insert("D", 4);

if let Some((min_key, min_value)) = map.iter().next() {
    println!("min_key={} min_value={}", min_key, min_value); //=> min_key=A min_value=1
}
if let Some((max_key, max_value)) = map.iter().next_back() {
    println!("max_key={} max_value={}", max_key, max_value); //=> max_key=E max_value=5
}

環境情報

Cargo.toml
[package]
name = "sample"
version = "0.1.0"
edition = "2021"
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?