当前位置:网站首页>[rust notes] 14 set (Part 2)
[rust notes] 14 set (Part 2)
2022-07-05 06:04:00 【phial03】
aggregate 14.3
14.3-VecDeque<T>
Vec
It can efficiently add and remove elements at both ends of the queue . If you want to save the value in the middle of the queue ,Vec
The processing efficiency of is relatively slow .deque
std::collections::VecDeque<T>
: Implemented ring buffer , Support efficient addition and removal of front-end and back-end operations .deque.push_front(value)
: Add a value in front of the queue .deque.push_back(value)
: Add a value after the queue .deque.pop_front()
: Remove and return the value in front of the queue , returnOption<T>
, Returns when the queue is emptyNone
.deque.pop_back
: Remove and return the value after the queue , returnOption<T>
, Returns when the queue is emptyNone
.deque.front()
anddeque.back()
: Return the shared reference of the front-end and back-end elements of the queue , returnOption<T>
, Returns when the queue is emptyNone
.deque.front_mut()
anddeque.back_mut
: Returns modifiable references to the front-end and back-end elements of the queue , returnOption<&mut T>
.
Queues are not stored consecutively in memory , Not all methods of the inheriting slices . If you want to perform vector and slice operations on the queue data , Need to put
VecDeque
Convert toVec
, After the operation , Then switch back .Vec<T>
RealizedFrom<VecDeque<T>>
, thereforeVec::from(deque)
You can convert queues into vectors .VecDeque<T>
RealizedFrom<Vec<T>>
, thereforeVecDeque::from(vec)
You can convert vectors into queues .// The method of creating a queue by specifying elements use std::collections::VecDeque; let v = VecDeque::from(vec![1, 2, 3, 4]);
14.4-LinkedList<T>
Each value of the linked list is stored in a separate heap memory , Is a way to store sequence values .
std::collections::LinkedList<T>
It's a two-way listSupport
VecDeque
Part of the way :
- The method of operating the front and back ends of the sequence ;
- Iterator method ;
LinkedList::new()
etc.
Support the combination of two lists very quickly :
list1.append(&mut list2)
, holdlist2
All elements in are transferred tolist1
in .vec
andVecDeque
Also supportappend
Method , But many values will be transferred from one heap array to another .
14.5-BinaryHeap<T>
BinaryHeap<T>
Used to store loose elements , The maximum value will always bubble to the front of the queue .Common methods :
heap.push(value)
: Add values to the heap .heap.pop()
: Remove from the heap and return the maximum . The return type isOption<T>
, If the heap is empty, returnNone
.heap.peek()
: Returns the reference of the maximum value in the heap . The return type isOption<&T>
.
Also support
Vec
Part of the way :BinaryHeap::new()
;heap.len()
;heap.is_empty()
;heap.capacity()
;heap.clear()
;heap.append(&mut heap2)
.
Realize the built-in special type
Ord
Any type of , Can be saved inBinaryHeap
in .It is often used to make work queues :
Define a task structure , Based on priority
Ord
, Make high priority tasks bigger than low priority tasks . then , Create aBinaryHeap
Save all completed tasks . You can call.pop()
Method always returns the most important task to do next .have access to
while
Recycling consumption :while let Some(task) = heap.pop() { handle(task); }
BinaryHeap
It's an iterative type , They have their own.iter()
Method , The order of iterators is arbitrary .
14.6-HashMap<K, V>
and BTreeMap<K, V>
mapping (map) It's a key — It's worth it ( Called entry ) aggregate .
HashMap<K, V>
Save the keys and values in a hash table allocated on the heap , Therefore, the type of key is requiredK
Implement standard hashing and equality featuresHash
andEq
.BTreeMap<K, V>
Store entries in key order , The overall structure is tree , Therefore, the type of key is requiredK
RealizationOrd
.Rust Standard library of B Trees , Instead of balancing binary trees . The number of times a binary tree must search , Than B Few trees ; But search B The domain of trees (locality) Better .B Trees can bring together memory accesses , Instead of spreading it all over the heap . such CPU Caching is rarely missed , So as to significantly improve the speed .
How to create a map :
HashMap::new()
andBTreeMap::new()
Create a new empty mapping ;iter.collect()
: For slave keys — Value pairs create and populate newHashMap
orBTreeMap
.iter
Must be aIterator<Item=(K, V)>
The iterator .HashMap::with_capacity(n)
: You can create a new empty hash table , At least it can holdn
Entries .HashMap
Support capacity related methods separately :hash_map.capacity()
、hash_map.reserve(additional)
andhash_map.shrink_to_fit()
.
HashMap
and
BTreeMap
Jointly support the following core methods :
map.len()
: Return the number of entries .map.is_empty()
: staymap
Return when there is no entrytrue
.map.contains_key(&key)
: In the mapping, the key of another entry iskey
When to return to true
.map.get(&key)
: Search formap
Has givenkey
The entry of . If you find a matching entry , returnSome(r)
, amongr
Is the corresponding reference . Otherwise return toNone
.map.get_mut(&key)
: The function is the same as above , But return a modifiable reference to a value . The value can be modified at will , But the key pike mapping itself , Do not modify .map.insert(key, value)
: towardsmap
Insert entry in(key, value)
. If the mapping already exists askey
The entry of , Then a new value will be insertedvalue
, Overwrite the original value . If the original value is overwritten , Will return the original value , The return type isOption<V>
.map.extend(iterable)
: iterationiterable
Of(K, V)
entry , And put each key — Value pair insertionmap
in .map.append(&mut map2)
: takemap2
All entries of are transferred tomap
in ,map2
It's going to be empty .map.remove(&key)
: Find and removemap
The middle key iskey
The entry of . If any value is removed , The removed value is returned . The return type isOption<V>
.map.clear()
: Remove all entries .map[&key]
: Query the mapping with square bracket syntax . If it does not exist, it iskey
The entry of , Will be surprised , Similar to array access out of bounds .
BTreeMap<K, V>
Because you can sort and store entries by pressing the key , And support
btree_map.split_off(key)
:
- Can be
btree_map
Split in two ; - The key is less than
key
The entry of will be left inbtree_map
in . - Back to the new
BTreeMap<K, V>
Contains other entries .
- Can be
14.6.1 - entry
Entry
Item type : Used to eliminate redundant mapping lookup .let record = student_map.entry(name.to_string()).or_insert_with(Student);
student_map.entry(name.to_string)
Back toEntry
Values are similar to modifiable references that point to a location in a map ;If the reference is empty , be
.or_insert_with()
Method will insert a newStudent
.Entry
Is an enumerated type :// std::collections::hash_map pub enum Entry<'a, K: 'a, V: 'a> { Occupied(OccupiedEntry<'a, K, V>), Vacant(VacantEntry<'a, K, V>) }
establish
Entry
The method of value :map.entry(key)
.Return key is
key
OfEntry
.If there is no , Then return an empty
Entry
.Receive your own modifiable references , Return life matched
Entry
:pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V>
If the mapped key is
String
type , This method cannot be passed&str
Type references . At this point, give.entry()
Method to pass in the realString
.
Method of filling in empty entries :
map.entry(key).or_insert(value)
: Must ensuremap
The containing key iskey
The entry of , Default will be given if necessaryvalue
Insert new entry . Returns a modifiable reference to a new or existing value .// give an example : Count the votes let mut vote_counts: HashMap<String, usize> = HashMap::new(); for name in ballots { let count = vote_counts.entry(name).or_insert(0); *count += 1; // count The type of &mut usize. }
map.entry(key).or_insert_with(default_fn)
: The function is the same as above , But it will be called when a new entry needs to be createddefault_fn()
function , To produce default values . Ifmap
Already exists in forkey
The entry of , Will not be useddefault_fn()
.let mut word_occurrence: HashMap<String, HashSet<String>> = Hashmap::new(); for file in files { for word in read_words(file)? { let set = word_occurrence .entry(word) .or_insert_with(HashSet::new); set.insert(file.clone()); } }
14.6.2 - Mapping iteration
HashMap
Iterators support accessing mapped entries in any order ;BTreeMap
iterator , Entries must be accessed in key sequence .- The iteration of mapping has the following ways :
- Iterate by value (
for (k, v) in map
): produce(K, V)
Yes . This will consume mapping . - Iterate by shared reference (
for (k, v) in &map
): produce(&K, &V)
Yes . - Press to modify the reference iteration (
for (k, v) in &mut map
): produce(&K, &mut v)
Yes .
- Iterate by value (
- The iteration of mapping has the following common methods :
.iter()
and.iter_mut()
: Methods that return iterators and generate value references ;map.keys()
: Returns the iterator that generates the key reference .map.values()
: Returns the iterator that generates the value reference .map.values_mut()
: Returns an iterator that produces a modifiable value reference .
14.7-HashSet<T>
and BTreeSet<T>
Set
Set : Support rapid testing of membership and organization of values . A set will never contain multiple copies of the same value .let b1 = large_vector.contains("needle"); // Finding elements in vectors is slow , You need to check each element let b2 = large_hash_set.contains("needle"); // It is faster to find elements in the set , Support hash lookup
Sets are similar to key only mappings .
HashSet<T>
andBTreeSet<T>
Are implemented in the form of packaging types :HashSet::new()
andBTreeSet::new()
Create a new set .iter.collect()
Can be used to create a new set from any iterator . If duplicate values are generated , Then the duplicate value will be cleared .HashSet::with_capacity(n)
Create emptyHashSet
, At leastn
It's worth .
HashSet<T>
andBTreeSet<T>
The common method :set.len()
: returnset
The number of median .set.is_empty()
: Return without element value in the settrue
.set.contains(&value)
: Include the given value in the setvalue
When to return totrue
.set.insert(value)
: Add... To the setvalue
. If the addition is successful, it will returntrue
, If the same value already exists in the set, it returnsfalse
.set.remove(&value)
: Remove from the setvalue
. If the removal is successful, returntrue
. If it's not worth it , Then return tofalse
.
Similar to mapping , The method of querying values by reference is also general , As long as you can
T
Borrow to this type .
14.7.1 - Set iteration
- There are two ways to iterate a set :
- Iterate by value :
for v in set
Generate members of the set , And consumption set . - Iterate by shared reference :
for v in &set
Generate shared references to set members .
- Iterate by value :
- Modifiable reference iteration sets are not supported . That is, modifiable references that cannot get values from the set .
set.iter()
Return iterator , produceset
References to members . HashSet
Iterators support accessing mapped entries in any order ;BTreeSet
iterator , Entries must be accessed in key sequence .
14.7.2 - Equal values are different —— Store different locations in memory
The method of getting the actual value stored in the set : These methods all return Option
, If set
Does not contain matching values , Then return to None
.
set.get(&value)
: returnset
Medium is equal tovalue
Shared references of members of , The return type isOption<&T>
.set.take(&value)
: Be similar toset.remove(&value)
, But return the removed value , The return type isOption<T>
.set.replace(value)
: Be similar toset.insert(value)
, But ifset
It already contains equal tovalue
Value , Then return the original value . The return type isOption<T>
14.7.3 - Whole set operation
- Methods of operating on the entire set :
set1.intersection(&set2)
: The return is also contained inset1
andset2
Iterators for all values in .&set1 & &set2
: returnset1
andset2
Intersection .set1.union(&set2)
: The return is also contained inset1
andset2
Kind of , Or only inset1
orset2
Iterator of the value of .&set1 | &set2
: Returns a new set containing all the values in these two sets .set1.difference(&set2)
: The return is contained inset1
But not included inset2
Iterator of values in .&set1 - &set2
: The return is contained inset1
But not included inset2
A new set of all these values .set1.symmetric_difference(&set2)
: The return is only contained inset1
in , Or only included inset2
in , But iterators that do not contain values in both sets .&set1 ^ &set2
: The return is only contained inset1
in , Or only included inset2
in , But a new set of values that are not included in both sets .
- Test the relationship between sets 3 Methods :
set1.is_disjoint(set2)
: If the intersection is empty , Then return totrue
.set1.is_subset(set2)
: Ifset1
yesset2
Subset , Then return totrue
.set1.is_superset(set2)
: Ifset1
yesset2
Superset , Then return totrue
.
- Set also supports
==
and!=
Equality test of : The two packages have the same value , Then they are equal .
14.8 - hash
14.8.1 - summary
std::hash::Hash
It is a special type of hashable type in the standard library .No matter where a value is saved , Or how to point to it , All should have the same hash code .
- The reference has the same hash code as the value it points to ;
Box
The same hash code as the boxed value ;- vector
vec
With slices that contain all their data&ved[..]
Have the same hash code ; String
With the same character as the reference&str
Have the same hash code .
Structure and enumeration are not implemented by default
Hash
, But you can derive an implementation :#[derive(Clone, PartialEq, Eq, Hash)] enum MN { ... }
If you manually implement for a type
PartialEq
, Then it must be realizedHash
.
14.8.2 - Use a custom hash algorithm
hash
Methods are generic .Complete protocol for computing hash codes :
use std::hash::{ Hash, Hasher, BuildHasher}; fn compute_hash<B, T>(builder: &B, value: &T) -> u64 where B: BuildHasher, T: Hash { let mut hasher = builder.build_hasher(); // Algorithm start value.hash(&mut hasher); // Incoming data hasher.finish() // Algorithm complete , produce u64 value . }
Rust By default
SipHash-1-3
Algorithm as hash algorithm . As long as there are differences , Every hash table uses unpredictable keys . So it can preventHashDoS
Denial of service attacks on , That is, the attacker deliberately uses hash conflict to start the worst performance in the server .If you want faster hash implementation , At the expense of security , Then you can use
fnv
Package implementationFowler-Noll-Vo
Hash algorithm .// stay Cargo.toml Add : [dependencies] fnv = "1.0" // Import mapping and hash types extern crate fnv; use fnv::{ FnvHashMap, FnvHashSet}; // Instead of HashMap and HashSet.
14.9 - Other sets
Rust Support in unsafe
Implementation in block C++ Data structure of : Original pointer 、 Manual memory management 、 place new
、 Show call destructors .
See 《Rust Programming 》( Jim - Brandy 、 Jason, - By orendov , Translated by lisongfeng ) Chapter 16
Original address
边栏推荐
猜你喜欢
实时时钟 (RTC)
Full Permutation Code (recursive writing)
Sword finger offer 53 - ii Missing numbers from 0 to n-1
数据可视化图表总结(二)
Introduction to LVS [unfinished (semi-finished products)]
【Jailhouse 文章】Look Mum, no VM Exits
Scope of inline symbol
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
[jailhouse article] jailhouse hypervisor
Individual game 12
随机推荐
【Jailhouse 文章】Performance measurements for hypervisors on embedded ARM processors
Control Unit 控制部件
One question per day 1447 Simplest fraction
1.13 - RISC/CISC
2017 USP Try-outs C. Coprimes
How many checks does kubedm series-01-preflight have
Configuration and startup of kubedm series-02-kubelet
【Rust 笔记】17-并发(上)
R语言【数据集的导入导出】
A reason that is easy to be ignored when the printer is offline
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
【Jailhouse 文章】Look Mum, no VM Exits
Implement a fixed capacity stack
智慧工地“水电能耗在线监测系统”
Educational codeforces round 109 (rated for Div. 2) C. robot collisions D. armchairs
927. 三等分 模拟
网络工程师考核的一些常见的问题:WLAN、BGP、交换机
Introduction to LVS [unfinished (semi-finished products)]
leetcode-6108:解密消息
[cloud native] record of feign custom configuration of microservices