rust data struct説明1--Vec 紹介-2
vec memory 管理
new vecの時、どのくらいのスペースが提供されているのですか?
//new vecの時、どのくらいのスペースが提供されているのですか?
let mut v = Vec::new();
println!("start: length{} capacity{}",v.len(),v.capacity());
//response
/*
qiminliu@qimindeMBP src % cargo run
start: length0 capacity0
*/
vec new時、不指定ならメモリーの空間が0になります
既存のvecのmemory space増加
let mut v = Vec::new();
println!("start: length{} capacity{}",v.len(),v.capacity());
//reserve がcapacityが増加
v.reserve(10);
println!("second: length{} capacity{}",v.len(),v.capacity());
//response
/*
qiminliu@qimindeMBP src % cargo run
start: length0 capacity0
second: length0 capacity10
*/
vec続き
memroy関するの資料は以下に参考してください
https://doc.rust-lang.org/nomicon/vec/vec.html
VecDeque使用
概念
VecDequeはdouble-ended queueです。以下に図を説明できます
create vecdeque(len,capacity=0)
use std::collections::VecDeque;
let deque: VecDeque<u32> = VecDeque::new();
create vecdeque(len=0,capacityが自由設定)
use std::collections::VecDeque;
//len=0、 capacity=10
let deque: VecDeque<u32> = VecDeque::with_capacity(10);
get an element
use std::collections::VecDeque;
let mut v = VecDeque::new();
v.push_back(8);
v.push_back(9);
v.push_back(10);
//getは頭から貰います
println!("{:?}",v.get(1));
println!("{:?}",v.get(0));
println!("{:?}",v.get(2));
//response
/*
qiminliu@qimindeMBP src % cargo run
Some(9)
Some(8)
Some(10)
*/
v +----0----+---1---+---2----+ //index position
| 8 | 9 | 10 | //value
element処理の纏め
#no need mut
v.get(index) -> Provides a reference to the element at the given index.
v.get_mut(index) -> Provides a mutable reference to the element at the given index.
v.front() -> Provides a reference to the front element, or None if the deque is empty.
v.back() ->Provides a reference to the back element, or None if the deque is empty.
#need mut
v.push_front(value) -> Prepends an element to the deque.
v.push_back(value) -> Appends an element to the back of the deque.
v.swap(value1,value2)-> Swaps elements at indices value1 and value2.
v.front_mut() ->Provides a mutable reference to the front element, or None if the deque is empty.
v.back_mut() ->Provides a mutable reference to the back element, or None if the deque is empty.
v.pop_front() ->Removes the first element and returns it, or None if the deque is empty.
v.insert(index,value)->Inserts an element at index within the deque, shifting all elements with indices greater than or equal to index towards the back.
v.remove(index). ->Removes and returns the element at index from the deque. Whichever end is closer to the removal point will be moved to make room, and all the affected elements will be moved to new positions. Returns None if index is out of bounds.