pub struct Counter<T: Hash + Eq, N = usize> { /* private fields */ }
Implementations§
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Create a new, empty Counter
with the specified capacity.
Note that capacity
in this case indicates how many distinct items may be counted without reallocation.
It is not related to the total number of items which may be counted.
For example, "aaa"
requires a capacity of 1. "abc"
requires a capacity of 3.
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn init<I>(iterable: I) -> Selfwhere
I: IntoIterator<Item = T>,
👎Deprecated: prefer the FromIterator
/collect
interface
pub fn init<I>(iterable: I) -> Selfwhere
I: IntoIterator<Item = T>,
FromIterator
/collect
interfaceCreate a new Counter
initialized with the given iterable.
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn update<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
pub fn update<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
Add the counts of the elements from the given iterable to this counter.
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn subtract<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
pub fn subtract<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
Remove the counts of the elements from the given iterable to this counter.
Non-positive counts are automatically removed.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.subtract("abba".chars());
let expect = [('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn most_common(&self) -> Vec<(T, N)>
pub fn most_common(&self) -> Vec<(T, N)>
Create a vector of (elem, frequency)
pairs, sorted most to least common.
let mc = "pappaopolo".chars().collect::<Counter<_>>().most_common();
let expected = vec![('p', 4), ('o', 3), ('a', 2), ('l', 1)];
assert_eq!(mc, expected);
Note that the ordering of duplicates is unstable.
Sourcepub fn most_common_tiebreaker<F>(&self, tiebreaker: F) -> Vec<(T, N)>
pub fn most_common_tiebreaker<F>(&self, tiebreaker: F) -> Vec<(T, N)>
Create a vector of (elem, frequency)
pairs, sorted most to least common.
In the event that two keys have an equal frequency, use the supplied ordering function to further arrange the results.
For example, we can sort reverse-alphabetically:
let counter = "eaddbbccc".chars().collect::<Counter<_>>();
let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a));
let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)];
assert_eq!(by_common, expected);
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn most_common_ordered(&self) -> Vec<(T, N)>
pub fn most_common_ordered(&self) -> Vec<(T, N)>
Create a vector of (elem, frequency)
pairs, sorted most to least common.
In the event that two keys have an equal frequency, use the natural ordering of the keys to further sort the results.
§Examples
let mc = "abracadabra".chars().collect::<Counter<_>>().most_common_ordered();
let expect = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)];
assert_eq!(mc, expect);
§Time complexity
O(n * log n), where n is the number of items in the counter. If all you want is
the top k items and k < n then it can be more efficient to use
k_most_common_ordered
.
Sourcepub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)>
pub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)>
Returns the k
most common items in decreasing order of their counts.
The returned vector is the same as would be obtained by calling most_common_ordered
and
then truncating the result to length k
. In particular, items with the same count are
sorted in increasing order of their keys. Further, if k
is greater than the length of
the counter then the returned vector will have length equal to that of the counter, not
k
.
§Examples
let counter: Counter<_> = "abracadabra".chars().collect();
let top3 = counter.k_most_common_ordered(3);
assert_eq!(top3, vec![('a', 5), ('b', 2), ('r', 2)]);
§Time complexity
This method can be much more efficient than most_common_ordered
when k is much
smaller than the length of the counter n. When k = 1 the algorithm is equivalent
to finding the minimum (or maximum) of n items, which requires n - 1 comparisons. For
a fixed value of k > 1, the number of comparisons scales with n as n + O(log n)
and the number of swaps scales as O(log n). As k approaches n, this algorithm
approaches a heapsort of the n items, which has complexity O(n * log n).
For values of k close to n the sorting algorithm used by most_common_ordered
will
generally be faster than the heapsort used by this method by a small constant factor.
Exactly where the crossover point occurs will depend on several factors. For small k
choose this method. If k is a substantial fraction of n, it may be that
most_common_ordered
is faster. If performance matters in your application then it may
be worth experimenting to see which of the two methods is faster.
Source§impl<T, N> Counter<T, N>
impl<T, N> Counter<T, N>
Sourcepub fn is_superset(&self, other: &Self) -> bool
pub fn is_superset(&self, other: &Self) -> bool
Test whether this counter is a superset of another counter. This is true if for all elements in this counter and the other, the count in this counter is greater than or equal to the count in the other.
c.is_superset(&d);
-> c.iter().all(|(x, n)| n >= d[x]) && d.iter().all(|(x, n)| c[x] >= n)
let c = "aaabbc".chars().collect::<Counter<_>>();
let mut d = "abb".chars().collect::<Counter<_>>();
assert!(c.is_superset(&d));
d[&'e'] = 1;
assert!(!c.is_superset(&d));
Sourcepub fn is_subset(&self, other: &Self) -> bool
pub fn is_subset(&self, other: &Self) -> bool
Test whether this counter is a subset of another counter. This is true if for all elements in this counter and the other, the count in this counter is less than or equal to the count in the other.
c.is_subset(&d);
-> c.iter().all(|(x, n)| n <= d[x]) && d.iter().all(|(x, n)| c[x] <= n)
let mut c = "abb".chars().collect::<Counter<_>>();
let mut d = "aaabbc".chars().collect::<Counter<_>>();
assert!(c.is_subset(&d));
c[&'e'] = 1;
assert!(!c.is_subset(&d));
Methods from Deref<Target = HashMap<T, N>>§
1.0.0 · Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
This number is a lower bound; the HashMap<K, V>
might be able to hold
more, but is guaranteed to be able to hold at least this many.
§Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);
1.0.0 · Sourcepub fn keys(&self) -> Keys<'_, K, V>
pub fn keys(&self) -> Keys<'_, K, V>
An iterator visiting all keys in arbitrary order.
The iterator element type is &'a K
.
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for key in map.keys() {
println!("{key}");
}
§Performance
In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn values(&self) -> Values<'_, K, V>
pub fn values(&self) -> Values<'_, K, V>
An iterator visiting all values in arbitrary order.
The iterator element type is &'a V
.
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values() {
println!("{val}");
}
§Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.10.0 · Sourcepub fn values_mut(&mut self) -> ValuesMut<'_, K, V>
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>
An iterator visiting all values mutably in arbitrary order.
The iterator element type is &'a mut V
.
§Examples
use std::collections::HashMap;
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values_mut() {
*val = *val + 10;
}
for val in map.values() {
println!("{val}");
}
§Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, K, V>
pub fn iter(&self) -> Iter<'_, K, V>
An iterator visiting all key-value pairs in arbitrary order.
The iterator element type is (&'a K, &'a V)
.
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for (key, val) in map.iter() {
println!("key: {key} val: {val}");
}
§Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, K, V>
pub fn iter_mut(&mut self) -> IterMut<'_, K, V>
An iterator visiting all key-value pairs in arbitrary order,
with mutable references to the values.
The iterator element type is (&'a K, &'a mut V)
.
§Examples
use std::collections::HashMap;
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
// Update all values
for (_, val) in map.iter_mut() {
*val *= 2;
}
for (key, val) in &map {
println!("key: {key} val: {val}");
}
§Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
1.0.0 · Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the map contains no elements.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
1.6.0 · Sourcepub fn drain(&mut self) -> Drain<'_, K, V>
pub fn drain(&mut self) -> Drain<'_, K, V>
Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the map to optimize its implementation.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");
for (k, v) in a.drain().take(1) {
assert!(k == 1 || k == 2);
assert!(v == "a" || v == "b");
}
assert!(a.is_empty());
1.88.0 · Sourcepub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, K, V, F>
pub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, K, V, F>
Creates an iterator which uses a closure to determine if an element should be removed.
If the closure returns true, the element is removed from the map and yielded. If the closure returns false, or panics, the element remains in the map and will not be yielded.
Note that extract_if
lets you mutate every value in the filter closure, regardless of
whether you choose to keep or remove it.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain
with a negated predicate if you do not need the returned iterator.
§Examples
Splitting a map into even and odd keys, reusing the original map:
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
let extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
let mut evens = extracted.keys().copied().collect::<Vec<_>>();
let mut odds = map.keys().copied().collect::<Vec<_>>();
evens.sort();
odds.sort();
assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
1.18.0 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
In other words, remove all pairs (k, v)
for which f(&k, &mut v)
returns false
.
The elements are visited in unsorted (and unspecified) order.
§Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 4);
§Performance
In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
a.insert(1, "a");
a.clear();
assert!(a.is_empty());
1.9.0 · Sourcepub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the map’s BuildHasher
.
§Examples
use std::collections::HashMap;
use std::hash::RandomState;
let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();
1.0.0 · Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the HashMap
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
§Panics
Panics if the new allocation size overflows usize
.
§Examples
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
map.reserve(10);
1.57.0 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the HashMap
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling try_reserve
,
capacity will be greater than or equal to self.len() + additional
if
it returns Ok(())
.
Does nothing if capacity is already sufficient.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
use std::collections::HashMap;
let mut map: HashMap<&str, isize> = HashMap::new();
map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");
1.0.0 · Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
§Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);
1.56.0 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
pub fn shrink_to(&mut self, min_capacity: usize)
Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
If the current capacity is less than the lower limit, this is a no-op.
§Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to(10);
assert!(map.capacity() >= 10);
map.shrink_to(0);
assert!(map.capacity() >= 2);
1.0.0 · Sourcepub fn entry(&mut self, key: K) -> Entry<'_, K, V>
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
Gets the given key’s corresponding entry in the map for in-place manipulation.
§Examples
use std::collections::HashMap;
let mut letters = HashMap::new();
for ch in "a short treatise on fungi".chars() {
letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
}
assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);
1.0.0 · Sourcepub fn get<Q>(&self, k: &Q) -> Option<&V>
pub fn get<Q>(&self, k: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
1.40.0 · Sourcepub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
Returns the key-value pair corresponding to the supplied key. This is potentially useful:
- for key types where non-identical keys can be considered equal;
- for getting the
&K
stored key value from a borrowed&Q
lookup key; or - for getting a reference to a key with the same lifetime as the collection.
The supplied key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Debug)]
struct S {
id: u32,
name: &'static str, // ignored by equality and hashing operations
}
impl PartialEq for S {
fn eq(&self, other: &S) -> bool {
self.id == other.id
}
}
impl Eq for S {}
impl Hash for S {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);
let mut map = HashMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);
1.86.0 · Sourcepub fn get_disjoint_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<&mut V>; N]
pub fn get_disjoint_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
Attempts to get mutable references to N
values in the map at once.
Returns an array of length N
with the results of each query. For soundness, at most one
mutable reference will be returned to any value. None
will be used if the key is missing.
This method performs a check to ensure there are no duplicate keys, which currently has a time-complexity of O(n^2), so be careful when passing many keys.
§Panics
Panics if any keys are overlapping.
§Examples
use std::collections::HashMap;
let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
// Get Athenæum and Bodleian Library
let [Some(a), Some(b)] = libraries.get_disjoint_mut([
"Athenæum",
"Bodleian Library",
]) else { panic!() };
// Assert values of Athenæum and Library of Congress
let got = libraries.get_disjoint_mut([
"Athenæum",
"Library of Congress",
]);
assert_eq!(
got,
[
Some(&mut 1807),
Some(&mut 1800),
],
);
// Missing keys result in None
let got = libraries.get_disjoint_mut([
"Athenæum",
"New York Public Library",
]);
assert_eq!(
got,
[
Some(&mut 1807),
None
]
);
use std::collections::HashMap;
let mut libraries = HashMap::new();
libraries.insert("Athenæum".to_string(), 1807);
// Duplicate keys panic!
let got = libraries.get_disjoint_mut([
"Athenæum",
"Athenæum",
]);
1.86.0 · Sourcepub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<&mut V>; N]
pub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
Attempts to get mutable references to N
values in the map at once, without validating that
the values are unique.
Returns an array of length N
with the results of each query. None
will be used if
the key is missing.
For a safe alternative see get_disjoint_mut
.
§Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
§Examples
use std::collections::HashMap;
let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
// SAFETY: The keys do not overlap.
let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([
"Athenæum",
"Bodleian Library",
]) }) else { panic!() };
// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_disjoint_unchecked_mut([
"Athenæum",
"Library of Congress",
]) };
assert_eq!(
got,
[
Some(&mut 1807),
Some(&mut 1800),
],
);
// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_disjoint_unchecked_mut([
"Athenæum",
"New York Public Library",
]) };
// Missing keys result in None
assert_eq!(got, [Some(&mut 1807), None]);
1.0.0 · Sourcepub fn contains_key<Q>(&self, k: &Q) -> bool
pub fn contains_key<Q>(&self, k: &Q) -> bool
Returns true
if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
1.0.0 · Sourcepub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
*x = "b";
}
assert_eq!(map[&1], "b");
1.0.0 · Sourcepub fn insert(&mut self, k: K, v: V) -> Option<V>
pub fn insert(&mut self, k: K, v: V) -> Option<V>
Inserts a key-value pair into the map.
If the map did not have this key present, None
is returned.
If the map did have this key present, the value is updated, and the old
value is returned. The key is not updated, though; this matters for
types that can be ==
without being identical. See the module-level
documentation for more.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);
map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
Sourcepub fn try_insert(
&mut self,
key: K,
value: V,
) -> Result<&mut V, OccupiedError<'_, K, V>>
🔬This is a nightly-only experimental API. (map_try_insert
)
pub fn try_insert( &mut self, key: K, value: V, ) -> Result<&mut V, OccupiedError<'_, K, V>>
map_try_insert
)Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.
If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.
§Examples
Basic usage:
#![feature(map_try_insert)]
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
let err = map.try_insert(37, "b").unwrap_err();
assert_eq!(err.entry.key(), &37);
assert_eq!(err.entry.get(), &"a");
assert_eq!(err.value, "b");
1.0.0 · Sourcepub fn remove<Q>(&mut self, k: &Q) -> Option<V>
pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
Removes a key from the map, returning the value at the key if the key was previously in the map.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
1.27.0 · Sourcepub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
Removes a key from the map, returning the stored key and value if the key was previously in the map.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove_entry(&1), Some((1, "a")));
assert_eq!(map.remove(&1), None);
Trait Implementations§
Source§impl<I, T, N> Add<I> for Counter<T, N>
impl<I, T, N> Add<I> for Counter<T, N>
Source§fn add(self, rhs: I) -> Self::Output
fn add(self, rhs: I) -> Self::Output
Consume self
producing a Counter
like self
updated with the counts of
the elements of I
.
let counter = "abbccc".chars().collect::<Counter<_>>();
let new_counter = counter + "aeeeee".chars();
let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
.iter().cloned().collect();
assert_eq!(new_counter.into_map(), expected);
Source§impl<T, N> Add for Counter<T, N>
impl<T, N> Add for Counter<T, N>
Source§fn add(self, rhs: Counter<T, N>) -> Self::Output
fn add(self, rhs: Counter<T, N>) -> Self::Output
Add two counters together.
out = c + d;
-> out[x] == c[x] + d[x]
for all x
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c + d;
let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
Source§impl<I, T, N> AddAssign<I> for Counter<T, N>
impl<I, T, N> AddAssign<I> for Counter<T, N>
Source§fn add_assign(&mut self, rhs: I)
fn add_assign(&mut self, rhs: I)
Directly add the counts of the elements of I
to self
.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter += "aeeeee".chars();
let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
.iter().cloned().collect();
assert_eq!(counter.into_map(), expected);
Source§impl<T, N> AddAssign for Counter<T, N>
impl<T, N> AddAssign for Counter<T, N>
Source§fn add_assign(&mut self, rhs: Self)
fn add_assign(&mut self, rhs: Self)
Add another counter to this counter.
c += d;
-> c[x] += d[x]
for all x
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c += d;
let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
Source§impl<T, N> BitAnd for Counter<T, N>
impl<T, N> BitAnd for Counter<T, N>
Source§fn bitand(self, rhs: Counter<T, N>) -> Self::Output
fn bitand(self, rhs: Counter<T, N>) -> Self::Output
Returns the intersection of self
and rhs
as a new Counter
.
out = c & d;
-> out[x] == min(c[x], d[x])
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c & d;
let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
Source§impl<T, N> BitAndAssign for Counter<T, N>
impl<T, N> BitAndAssign for Counter<T, N>
Source§fn bitand_assign(&mut self, rhs: Counter<T, N>)
fn bitand_assign(&mut self, rhs: Counter<T, N>)
Updates self
with the intersection of self
and rhs
c &= d;
-> c[x] == min(c[x], d[x])
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c &= d;
let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
Source§impl<T, N> BitOr for Counter<T, N>
impl<T, N> BitOr for Counter<T, N>
Source§fn bitor(self, rhs: Counter<T, N>) -> Self::Output
fn bitor(self, rhs: Counter<T, N>) -> Self::Output
Returns the union of self
and rhs
as a new Counter
.
out = c | d;
-> out[x] == max(c[x], d[x])
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c | d;
let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
Source§impl<T, N> BitOrAssign for Counter<T, N>
impl<T, N> BitOrAssign for Counter<T, N>
Source§fn bitor_assign(&mut self, rhs: Counter<T, N>)
fn bitor_assign(&mut self, rhs: Counter<T, N>)
Updates self
with the union of self
and rhs
c |= d;
-> c[x] == max(c[x], d[x])
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c |= d;
let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
Source§impl<'a, T, N> Extend<(&'a T, &'a N)> for Counter<T, N>
impl<'a, T, N> Extend<(&'a T, &'a N)> for Counter<T, N>
Source§fn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I)
Extend a counter with (item, count)
tuples.
You can extend a Counter
with another Counter
:
let mut counter = "abbccc".chars().collect::<Counter<_>>();
let another = "bccddd".chars().collect::<Counter<_>>();
counter.extend(&another);
let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<T, N> Extend<(T, N)> for Counter<T, N>
impl<T, N> Extend<(T, N)> for Counter<T, N>
Source§fn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I)
Extend a counter with (item, count)
tuples.
The counts of duplicate items are summed.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.extend([('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter().cloned());
let expect = [('a', 6), ('b', 4), ('c', 6)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<T, N> Extend<T> for Counter<T, N>
impl<T, N> Extend<T> for Counter<T, N>
Source§fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
Extend a Counter
with an iterator of items.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.extend("bccddd".chars());
let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<T, N> FromIterator<(T, N)> for Counter<T, N>
impl<T, N> FromIterator<(T, N)> for Counter<T, N>
Source§fn from_iter<I: IntoIterator<Item = (T, N)>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = (T, N)>>(iter: I) -> Self
Creates a counter from (item, count)
tuples.
The counts of duplicate items are summed.
let counter = [('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter()
.cloned().collect::<Counter<_>>();
let expect = [('a', 5), ('b', 2), ('c', 3)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§impl<T, N> FromIterator<T> for Counter<T, N>
impl<T, N> FromIterator<T> for Counter<T, N>
Source§fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Self
Produce a Counter
from an iterator of items. This is called automatically
by Iterator::collect()
.
let counter = "abbccc".chars().collect::<Counter<_>>();
let expect = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
Source§impl<T, Q, N> Index<&Q> for Counter<T, N>
impl<T, Q, N> Index<&Q> for Counter<T, N>
Source§fn index(&self, key: &Q) -> &N
fn index(&self, key: &Q) -> &N
Index in immutable contexts.
Returns a reference to a zero
value for missing keys.
let counter = "aabbcc".chars().collect::<Counter<_>>();
assert_eq!(counter[&'a'], 2);
assert_eq!(counter[&'b'], 2);
assert_eq!(counter[&'c'], 2);
assert_eq!(counter[&'d'], 0);
Note that the zero
is a struct field but not one of the values of the inner
HashMap
. This method does not modify any existing value.
let counter = "".chars().collect::<Counter<_>>();
assert_eq!(counter[&'a'], 0);
assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
Source§impl<T, Q, N> IndexMut<&Q> for Counter<T, N>
impl<T, Q, N> IndexMut<&Q> for Counter<T, N>
Source§fn index_mut(&mut self, key: &Q) -> &mut N
fn index_mut(&mut self, key: &Q) -> &mut N
Index in mutable contexts.
If the given key is not present, creates a new entry and initializes it with a zero
value.
let mut counter = "aabbcc".chars().collect::<Counter<_>>();
counter[&'c'] += 1;
counter[&'d'] += 1;
assert_eq!(counter[&'c'], 3);
assert_eq!(counter[&'d'], 1);
Unlike Index::index
, the returned mutable reference to the zero
is actually one of the
values of the inner HashMap
.
let mut counter = "".chars().collect::<Counter<_>>();
assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
let _ = &mut counter[&'a'];
assert_eq!(counter.get(&'a'), Some(&0));
Source§impl<'a, T, N> IntoIterator for &'a Counter<T, N>
impl<'a, T, N> IntoIterator for &'a Counter<T, N>
Source§impl<'a, T, N> IntoIterator for &'a mut Counter<T, N>
impl<'a, T, N> IntoIterator for &'a mut Counter<T, N>
Source§fn into_iter(self) -> Self::IntoIter
fn into_iter(self) -> Self::IntoIter
Creates an iterator that provides mutable references to the counts, but keeps the keys immutable.
§Examples
let mut counter: Counter<_> = "aaab".chars().collect();
for (item, count) in &mut counter {
if *item == 'a' {
// 'a' is so great it counts as 2
*count *= 2;
}
}
assert_eq!(counter[&'a'], 6);
assert_eq!(counter[&'b'], 1);
Source§impl<T, N> IntoIterator for Counter<T, N>
impl<T, N> IntoIterator for Counter<T, N>
Source§fn into_iter(self) -> Self::IntoIter
fn into_iter(self) -> Self::IntoIter
Consumes the Counter
to produce an iterator that owns the values it returns.
§Examples
let counter: Counter<_> = "aaab".chars().collect();
let vec: Vec<_> = counter.into_iter().collect();
for (item, count) in &vec {
if item == &'a' {
assert_eq!(count, &3);
}
if item == &'b' {
assert_eq!(count, &1);
}
}
Source§impl<I, T, N> Sub<I> for Counter<T, N>
impl<I, T, N> Sub<I> for Counter<T, N>
Source§fn sub(self, rhs: I) -> Self::Output
fn sub(self, rhs: I) -> Self::Output
Consume self
producing a Counter
like self
with the counts of the
elements of I
subtracted, keeping only positive values.
let c = "aaab".chars().collect::<Counter<_>>();
let e = c - "abb".chars();
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
Source§impl<T, N> Sub for Counter<T, N>
impl<T, N> Sub for Counter<T, N>
Source§fn sub(self, rhs: Counter<T, N>) -> Self::Output
fn sub(self, rhs: Counter<T, N>) -> Self::Output
Subtract (keeping only positive values).
out = c - d;
-> out[x] == c[x] - d[x]
for all x
,
keeping only items with a value greater than N::zero()
.
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c - d;
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
Source§impl<I, T, N> SubAssign<I> for Counter<T, N>
impl<I, T, N> SubAssign<I> for Counter<T, N>
Source§fn sub_assign(&mut self, rhs: I)
fn sub_assign(&mut self, rhs: I)
Directly subtract the counts of the elements of I
from self
,
keeping only items with a value greater than N::zero()
.
let mut c = "aaab".chars().collect::<Counter<_>>();
c -= "abb".chars();
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
Source§impl<T, N> SubAssign for Counter<T, N>
impl<T, N> SubAssign for Counter<T, N>
Source§fn sub_assign(&mut self, rhs: Self)
fn sub_assign(&mut self, rhs: Self)
Subtract (keeping only positive values).
c -= d;
-> c[x] -= d[x]
for all x
,
keeping only items with a value greater than N::zero()
.
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c -= d;
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);