LoginSignup
0
0

More than 1 year has passed since last update.

rust data struct説明1--Vec 紹介-1

Last updated at Posted at 2023-04-01

rust data struct説明1--Vec 紹介-1

モジュール説明

module std::collectionsは基本のdata structを含めています(standard implementations),この内容がこのdata structを紹介します

タープ分類

module std::collectionsは分類すると、以下の分類になりました
Sequences: vec, VecDeque, LinkedList
Maps:     HashMap, BreeMap
Sets:    HashSet,BTreeSet
Misc:   BinaryHeap

Sqeuences-->Vec 紹介

vecは何の物?arrayと区別

vecは動的配列、arrayは静的配列です、以下は区別です
静的配列とは、配列のサイズがコンパイル時に決定されていることを意味し、
メモリ割り当てもコンパイル時に実行されます。
これは、プログラミング中に配列のサイズがわかっている場合に適しており、
配列のサイズは変更されません。
動的配列は、プログラムの実行時に動的に割り当てられるメモリであり、
そのサイズは要件に応じて変更できます。
プログラミング中に配列のサイズを決定できない場合や、
特定の状況に応じて動的に調整する必要がある場合に適しています

create vec

//方法1 
//create writeable vec
let mut vec1 = Vec::new() 
//create readable vec
let  vec1 = Vec::new() 

//方法2
// vec!というmarcoを利用する、新たのvecを誕生する
// writeable
let mut vec1 = vec![1, 2, 3];
//readable
let vec1 = vec![1, 2, 3];

add vec

// {}.pushの方法で増加データ,FIFO
let mut v = Vec::new();
v.push(5);
v.push(6)

1680333177775.jpg

get an element from the tail

let mut v = Vec::new();
v.push(5);
v.push(6)
// pop方法でデータを獲得
let a = v.pop();
println!("{:?}",a);
//結果;Some(6). 
//Someは何のものですか?初心者には難しいです、Some == have valueと考えるのは良いです

get an element in the vec

    let v = vec![1,2,3,4,5,6];
    let third: &i32 = &v[2];
    println!("third element is {}",third);
    match v.get(2) {
        Some(third) => println!("the third element is {}",third),
        None => println!("there is no third element"),
    }

traversal vec

let mut v = vec![100,2,33];
    for i in &mut v {
        //get an index from v,need write(mut )
        println!("{}",i);
        *i += 50;
        println!("L2 is {}",i);
    }

Use enums to store multiple types

enum SpreadsheetCell{
    Int(i32),
    Float(f64),
    Text(String),
}

let row = vec![
    SpreadsheetCell::Int(3),
    SpreadsheetCell::Float(64),
    SpreadsheetCell::Text(String),
];

 vecのmemory に関する

vecは動的配列です
let mut vec1 = vec![1, 2, 3]; --> 3 memory block occpued
let mut vec2 = Vec::with_capacity(10); --> 10 memory block occpued
vec2.resize(10, 0);  --> 10 memory block value is 0 -> [0,0,0,0,0,0,0,0,0,0] equal
vec.push(2);  --> add one memory block
vec.pop(1);  --> mark one memory block recycle (標識だけ)
このvecのlifetimes終わるの時、memoryを回収する

vec index

let v = vec![0, 2, 4, 6];
println!("{}", v[1]); // it will display '2'

v      +----0----+---1---+---2----+--3-----+   //index position
       |    0   |    2   |  4     | 6      |   //value
0
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
0
0