use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("KL", "Kerala");
println!("{:?}", map);
use std::collections::HashMap;
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("Blue".to_string(), 10);
map.insert("Yellow".to_string(), 50);
1. new + insert
let mut map = HashMap::new();
map.insert("apple", 3);
let keys = ["a", "b"];
let vals = [1, 2];
let map: HashMap<_, _> = keys.iter().zip(vals.iter()).collect();
3. 배열 리터럴 (Rust 1.56+)
let map = HashMap::from([
("pi", 3.14),
("e", 2.71),
]);
값 조회 | map.get("Blue") → Some(&10) |
존재하지 않으면 삽입 | map.entry("Red").or_insert(0); |
값 업데이트 | *map.entry("Blue").or_insert(0) += 5; |
전체 순회 | for (k, v) in &map { println!("{k}: {v}"); } |
use std::collections::HashMap;
let text = "hello world wonderful world";
let mut freq: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
*freq.entry(word).or_insert(0) += 1;
}
println!("{freq:?}");
// 출력: {"world": 2, "wonderful": 1, "hello": 1}
타입 | HashMap<K, V> |
모듈 | std::collections |
시간 복잡도 | 평균 O(1) |
중복 키 | 자동 덮어쓰기 |
순서 보장 | ❌ (필요 시 IndexMap 사용) |
기본 해셔 | SipHash-1-3 |
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert("Apple");
println!("집합 크기: {}", set.len());
Rust의 HashSet은 Eq + Hash 트레잇을 구현한 고유한 요소들을 해시 테이블로 관리하며, 삽입·삭제·조회가 평균 O(1)인 집합 자료구조다.
use std::collections::HashSet;
fn main() {
let mut set = HashSet::new();
set.insert("apple");
set.insert("banana");
set.insert("apple"); // 중복 삽입 무시됨
println!("집합 크기: {}", set.len()); // 2
println!("banana 포함 여부: {}", set.contains("banana")); // true
}
항목설명
중복 허용 | ❌ (동일한 값은 한 번만 저장) |
순서 보장 | ❌ (삽입 순서와 무관) |
필요 트레잇 | 저장하려는 타입은 Eq + Hash 구현 필수 |
내부 구조 | HashMap<T, ()> |
평균 시간복잡도 | 삽입, 삭제, 조회 모두 O(1) |
use std::collections::HashSet;
fn main() {
let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<_> = [2, 3, 4].iter().cloned().collect();
let union: HashSet<_> = a.union(&b).collect(); // 합집합
let diff: HashSet<_> = a.difference(&b).collect(); // 차집합
let inter: HashSet<_> = a.intersection(&b).collect(); // 교집합
println!("합집합: {:?}", union); // {1, 2, 3, 4}
println!("차집합: {:?}", diff); // {1}
println!("교집합: {:?}", inter); // {2, 3}
}
HashSet<T>
↓ (내부)
HashMap<T, ()>
↓
┌─────────────┐
│ 버킷 배열 │
│ [0] → T1 │
│ [1] → ∅ │
│ [2] → T2 │
└─────────────┘
참고
HashSet in std::collections - Rust
Adds a value to the set, replacing the existing value, if any, that is equal to the given one. Returns the replaced value. §Examples use std::collections::HashSet; let mut set = HashSet::new(); set.insert(Vec:: ::new()); assert_eq!(set.get(&[][..]).unwrap
doc.rust-lang.org
Rust에서 두 세트 간의 차이 계산하기
이 자습서에서는 두 집합 간의 차이를 계산하는 내장 함수에 대해 설명합니다.
www.delftstack.com
러스트 기초편 1 / 2 (0) | 2025.08.30 |
---|---|
오류 처리 (Result, panic!) (1) | 2025.08.07 |
배열과 벡터 (0) | 2025.08.04 |
함수 + 반환값 (0) | 2025.08.03 |
조건문 + 반복문 (0) | 2025.08.03 |