Rust Guide > Documentation > Collections > BTreeSet

Introduction

The BTreeSet class in Rust provides a balanced binary tree set. It is a collection that maintains its elements in sorted order and ensures no duplicates. This makes it a suitable choice for scenarios where sorted data and fast lookups are required.

Using BTreeSet

The BTreeSet class can be used to create and manage a sorted set of unique values. Here is a basic example:

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in &set {
        println!("{}", value);
    }
}
// Output:
// 1
// 2
// 3

Key Methods

Below are some of the key methods exposed by the BTreeSet class:

new

Creates a new, empty BTreeSet.

use std::collections::BTreeSet;

fn main() {
    let set: BTreeSet<i32> = BTreeSet::new();
    println!("Set created.");
}
// Output: Set created.

insert

Adds a value to the set. Returns true if the value was not already present in the set.

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.insert(2);
    println!("{:?}", set);
}
// Output: {1, 2}

remove

Removes a value from the set. Returns true if the value was present in the set.

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.remove(&1);
    println!("{:?}", set);
}
// Output: {}

contains

Checks if the set contains a particular value. Returns true if the value is present.

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    println!("{}", set.contains(&1));
}
// Output: true

len

Returns the number of elements in the set.

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.insert(2);
    println!("Set length: {}", set.len());
}
// Output: Set length: 2

iter

Returns an iterator over the elements of the set in sorted order.

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in set.iter() {
        println!("{}", value);
    }
}
// Output:
// 1
// 2
// 3

Example Usage

Example 1: Basic Usage

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.insert(2);
    set.insert(3);
    println!("{:?}", set);
}
// Output: {1, 2, 3}

Example 2: Removing Elements

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.insert(2);
    set.remove(&1);
    println!("{:?}", set);
}
// Output: {2}

Example 3: Checking for Elements

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    println!("Contains 1: {}", set.contains(&1));
    println!("Contains 2: {}", set.contains(&2));
}
// Output:
// Contains 1: true
// Contains 2: false

Example 4: Iterating Over Elements

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in &set {
        println!("{}", value);
    }
}
// Output:
// 1
// 2
// 3

Example 5: Union of Sets

use std::collections::BTreeSet;

fn main() {
    let mut set1 = BTreeSet::new();
    set1.insert(1);
    set1.insert(2);

    let mut set2 = BTreeSet::new();
    set2.insert(2);
    set2.insert(3);

    let union_set: BTreeSet<_> = set1.union(&set2).cloned().collect();
    println!("{:?}", union_set);
}
// Output: {1, 2, 3}

Considerations

  • The BTreeSet ensures that elements are always sorted, which can be useful for range queries and ordered operations.
  • Compared to HashSet, BTreeSet may have higher overhead for some operations, but provides order guarantees.

See Also

  • HashSet - An unordered collection of unique values, providing faster operations for large sets.
  • BTreeMap - A key-value store based on a balanced binary tree, providing sorted keys.
  • Vec - A contiguous growable array type with heap-allocated contents.
  • LinkedList - A linked list allowing efficient insertion and removal at any point.