Ben Chuanlong Du's Blog

It is never too late to learn.

Vector in Rust

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. Summary of Collections in Rust has a good summary on when to each which collection in Rust.
In [2]:
use std::vec::Vec;

Construct a Vector

Construct an empty vector.

In [7]:
let v1: Vec<i32> = Vec::new();
v1
Out[7]:
[]
In [8]:
v1.len()
Out[8]:
0

Construct an empty vector with an (initial) capacity.

In [9]:
let w1: Vec<i32> = Vec::with_capacity(10);
w1
Out[9]:
[]
In [10]:
w1.len()
Out[10]:
0

Construct a vector of predefined values.

In [3]:
let v1 = vec![0, 1, 2, 30, 4, 5, 6, 7, 8, 9];
v1
Out[3]:
[0, 1, 2, 30, 4, 5, 6, 7, 8, 9]
In [4]:
v1.capacity()
Out[4]:
10

Construct a vector of 0's.

In [5]:
let v2: Vec<i32> = vec![0; 10];
v2
Out[5]:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In [6]:
v2.capacity()
Out[6]:
10

Construct of vector of a fixed value with a dynamic size.

In [7]:
let n = 10;
let v3: Vec<i32> = vec![100; n];
v3
Out[7]:
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

Define a mutable vector.

In [10]:
let mut v4: Vec<i32> = vec![0; n];
v4
Out[10]:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In [11]:
v4[0] = 1000;
v4
Out[11]:
[1000, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Vec is NOT Copiable

In [10]:
let vec1 = vec![1, 2, 3];
let vec2 = vec1;
println!("{:?}", vec1);
println!("{:?}", vec2);
let vec2 = vec1;
           ^^^^ value moved here
println!("{:?}", vec1);
                 ^^^^ value borrowed here after move
let vec1 = vec![1, 2, 3];
    ^^^^ move occurs because `vec1` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
borrow of moved value: `vec1`
In [12]:
let v1 = vec![1, 2, 3];
let v2 = &v1;
println!("{:?}", v1);
println!("{:?}", v2);
let v2 = &v1;
         ^^^ borrowed value does not live long enough
`v1` does not live long enough
let v2 = &v1;
         ^^^ borrow of `v1` occurs here
cannot move out of `v1` because it is borrowed

Vec is Clonable

In [2]:
let vec1 = vec![1, 2, 3];
vec1
Out[2]:
[1, 2, 3]
In [3]:
let vec2 = vec1.clone();
vec2
Out[3]:
[1, 2, 3]

Vector Slicing

A slice is a dynamically sized type representing a "view" into a sequence of elements of type T. The slice type is written as [T]. To use a slice type it generally has to be used behind a pointer, e.g., as &[T], which is a "shared slice" (often just called a "slice"). A shared slice does not own the data it points to but instead borrows it.

In [4]:
let v = vec![0, 1, 2, 30, 4, 5, 6, 7, 8, 9];
v
Out[4]:
[0, 1, 2, 30, 4, 5, 6, 7, 8, 9]
In [5]:
&v[0..3]
Out[5]:
[0, 1, 2]
In [6]:
&v[5..]
Out[6]:
[5, 6, 7, 8, 9]

Create a New Sub Vector

Create a New Sub Vector via Slicing

In [7]:
(&v[5..]).to_vec()
Out[7]:
[5, 6, 7, 8, 9]

Create a New Sub Vector via Iterator

In [9]:
v.iter().skip(6).collect::<Vec<_>>()
Out[9]:
[6, 7, 8, 9]

Reference to Vectors

In [26]:
{
    let v: Vec<i32> = Vec::new();
    let r = &v;
    println!("{:?}", r);
}
[]
Out[26]:
()
In [30]:
{
    let v: Vec<i32> = Vec::new();
    let mut r = &v;
    let v1: Vec<i32> = vec![0; 5];
    r = &v1;
    println!("{:?}", r);
}
[0, 0, 0, 0, 0]
Out[30]:
()
In [28]:
{
    let mut v: Vec<i32> = Vec::new();
    let r = &mut v;
    println!("{:?}", r);
}
[]
Out[28]:
()
In [2]:
let v = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
v
Out[2]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]:
v.chunks(3)
Out[3]:
Chunks { v: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], chunk_size: 3 }
In [4]:
v.chunks(3).collect::<Vec<_>>()
Out[4]:
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
In [2]:
let s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
In [3]:
let index = s.binary_search(&21);
index
Out[3]:
Ok(10)
In [4]:
index.is_ok()
Out[4]:
true
In [5]:
index.unwrap()
Out[5]:
10
In [9]:
let index = s.binary_search(&23);
index
Out[9]:
Err(11)
In [10]:
index.unwrap_err()
Out[10]:
11
In [7]:
s.binary_search(&100)
Out[7]:
Err(13)
In [8]:
s.binary_search(&-10)
Out[8]:
Err(0)
In [5]:
let s2: Vec<u64> = [2 as u64, 3 as u64, 5 as u64, 8 as u64].to_vec();
s2
Out[5]:
[2, 3, 5, 8]
In [7]:
s2.binary_search(&(2 as u64))
Out[7]:
Ok(0)

Sort a Vector

Sort an vector using the nature order.

In [5]:
let mut vec = vec![1, 5, 10, 2, 15];
vec.sort();
vec
Out[5]:
[1, 2, 5, 10, 15]
In [6]:
let mut vec = vec![1, 5, 10, 2, 15];
vec.sort_unstable();
vec
Out[6]:
[1, 2, 5, 10, 15]
In [11]:
let mut vec = vec![1, 5, 10, 2, 15];
vec.sort_by_key(|x| -x);
vec
Out[11]:
[15, 10, 5, 2, 1]
In [12]:
let mut vec = vec![1, 5, 10, 2, 15];
vec.sort_unstable_by_key(|x| -x);
vec
Out[12]:
[15, 10, 5, 2, 1]
In [20]:
let mut vec = vec!["bb", "a", "dddd", "ccc"];
vec.sort_by(|s1, s2| s1.len().cmp(&s2.len()));
vec
Out[20]:
["a", "bb", "ccc", "dddd"]
In [21]:
let mut vec = vec!["bb", "a", "dddd", "ccc"];
vec.sort_unstable_by(|s1, s2| s1.len().cmp(&s2.len()));
vec
Out[21]:
["a", "bb", "ccc", "dddd"]
In [22]:
let mut vec = vec!["bb", "a", "dddd", "ccc"];
vec.sort_by(|s1, s2| s1.len().cmp(&s2.len()).reverse());
vec
Out[22]:
["dddd", "ccc", "bb", "a"]
In [23]:
let mut vec = vec!["bb", "a", "dddd", "ccc"];
vec.sort_unstable_by(|s1, s2| s1.len().cmp(&s2.len()).reverse());
vec
Out[23]:
["dddd", "ccc", "bb", "a"]

Return a New Sorted Copy

In [16]:
:dep itertools = "0.10.1"
In [17]:
use itertools::Itertools;
In [18]:
let v = vec![1, 5, 10, 2, 15];
v
Out[18]:
[1, 5, 10, 2, 15]
In [19]:
v.iter().sorted()
Out[19]:
IntoIter([1, 2, 5, 10, 15])
In [21]:
v.iter().sorted().collect_vec()
Out[21]:
[1, 2, 5, 10, 15]

Sorted/Ordered Data Structures

https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html sorted map

https://doc.rust-lang.org/stable/std/collections/struct.BTreeSet.html# sort set

https://github.com/bluss/indexmap ordered (insertion order) hashmap similar to dict in Python 3.7+

Vector of Vector

In [2]:
let data: Vec<Vec<i32>> = Vec::new();
data
Out[2]:
[]
In [ ]:
data.push
In [ ]:

Comments