Collections - โครงสร้างข้อมูล
นอกจาก Vec แล้ว Rust มี Collections อื่นๆ ให้เลือกใช้ตามความเหมาะสม!
เลือก Collection ไหนดี?
Section titled “เลือก Collection ไหนดี?”| ต้องการ | ใช้ | O(operation) |
|---|---|---|
| เรียงลำดับ, index | Vec<T> | O(1) access |
| key-value | HashMap<K, V> | O(1) avg |
| ไม่ซ้ำ | HashSet<T> | O(1) avg |
| เรียงลำดับ key | BTreeMap<K, V> | O(log n) |
| เรียงลำดับ ไม่ซ้ำ | BTreeSet<T> | O(log n) |
| เพิ่ม/ลบหัวท้าย | VecDeque<T> | O(1) |
| ค่าสูงสุดก่อน | BinaryHeap<T> | O(log n) |
1. HashMap - Key-Value
Section titled “1. HashMap - Key-Value”use std::collections::HashMap;
fn main() { // สร้าง HashMap let mut scores = HashMap::new();
// เพิ่มข้อมูล scores.insert("Alice", 95); scores.insert("Bob", 87); scores.insert("Charlie", 92); println!("scores: {:?}", scores);
// เข้าถึง (return Option) let alice_score = scores.get("Alice"); println!("Alice: {:?}", alice_score); // Some(&95)
// ตรวจว่ามี key ไหม println!("has Alice: {}", scores.contains_key("Alice"));
// ลบ let removed = scores.remove("Bob"); println!("removed Bob: {:?}", removed);
// วนซ้ำ println!("=== ทุกคน ==="); for (name, score) in &scores { println!("{}: {}", name, score); }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google