Struct VecDeque
struct VecDeque<T, A: Allocator = crate::alloc::Global> { ... }
A double-ended queue implemented with a growable ring buffer.
The "default" usage of this type as a queue is to use push_back to add to
the queue, and pop_front to remove from the queue. extend and append
push onto the back in this manner, and iterating over VecDeque goes front
to back.
A VecDeque with a known list of items can be initialized from an array:
use VecDeque;
let deq = from;
Since VecDeque is a ring buffer, its elements are not necessarily contiguous
in memory. If you want to access the elements as a single slice, such as for
efficient sorting, you can use make_contiguous. It rotates the VecDeque
so that its elements do not wrap, and returns a mutable slice to the
now-contiguous element sequence.
Implementations
impl<T> VecDeque<T>
const fn new() -> VecDeque<T>Creates an empty deque.
Examples
use VecDeque; let deque: = new;fn with_capacity(capacity: usize) -> VecDeque<T>Creates an empty deque with space for at least
capacityelements.Examples
use VecDeque; let deque: = with_capacity;fn try_with_capacity(capacity: usize) -> Result<VecDeque<T>, TryReserveError>Creates an empty deque with space for at least
capacityelements.Errors
Returns an error if the capacity exceeds
isize::MAXbytes, or if the allocator reports allocation failure.Examples
# # #
impl<T, A: Allocator> VecDeque<T, A>
const fn new_in(alloc: A) -> VecDeque<T, A>Creates an empty deque.
Examples
use VecDeque; let deque: = new;fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A>Creates an empty deque with space for at least
capacityelements.Examples
use VecDeque; let deque: = with_capacity;fn get(self: &Self, index: usize) -> Option<&T>Provides a reference to the element at the given index.
Element at index 0 is the front of the queue.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; buf.push_back; assert_eq!;fn get_mut(self: &mut Self, index: usize) -> Option<&mut T>Provides a mutable reference to the element at the given index.
Element at index 0 is the front of the queue.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; buf.push_back; assert_eq!; if let Some = buf.get_mut assert_eq!;fn swap(self: &mut Self, i: usize, j: usize)Swaps elements at indices
iandj.iandjmay be equal.Element at index 0 is the front of the queue.
Panics
Panics if either index is out of bounds.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; assert_eq!; buf.swap; assert_eq!;fn capacity(self: &Self) -> usizeReturns the number of elements the deque can hold without reallocating.
Examples
use VecDeque; let buf: = with_capacity; assert!;fn reserve_exact(self: &mut Self, additional: usize)Reserves the minimum capacity for at least
additionalmore elements to be inserted in the given deque. Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore capacity can not be relied upon to be precisely minimal. Prefer
reserveif future insertions are expected.Panics
Panics if the new capacity overflows
usize.Examples
use VecDeque; let mut buf: = .into; buf.reserve_exact; assert!;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore elements to be inserted in the given deque. The collection may reserve more space to speculatively avoid frequent reallocations.Panics
Panics if the new capacity overflows
usize.Examples
use VecDeque; let mut buf: = .into; buf.reserve; assert!;fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve the minimum capacity for at least
additionalmore elements to be inserted in the given deque. After callingtry_reserve_exact, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
try_reserveif future insertions are expected.Errors
If the capacity overflows
usize, or the allocator reports a failure, then an error is returned.Examples
use TryReserveError; use VecDeque; # process_data.expect;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalmore elements to be inserted in the given deque. The collection may reserve more space to speculatively avoid frequent reallocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.Errors
If the capacity overflows
usize, or the allocator reports a failure, then an error is returned.Examples
use TryReserveError; use VecDeque; # process_data.expect;fn shrink_to_fit(self: &mut Self)Shrinks the capacity of the deque as much as possible.
It will drop down as close as possible to the length but the allocator may still inform the deque that there is space for a few more elements.
Examples
use VecDeque; let mut buf = with_capacity; buf.extend; assert_eq!; buf.shrink_to_fit; assert!;fn shrink_to(self: &mut Self, min_capacity: usize)Shrinks the capacity of the deque with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
Examples
use VecDeque; let mut buf = with_capacity; buf.extend; assert_eq!; buf.shrink_to; assert!; buf.shrink_to; assert!;fn truncate(self: &mut Self, len: usize)Shortens the deque, keeping the first
lenelements and dropping the rest.If
lenis greater or equal to the deque's current length, this has no effect.Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; assert_eq!; buf.truncate; assert_eq!;fn truncate_front(self: &mut Self, len: usize)Shortens the deque, keeping the last
lenelements and dropping the rest.If
lenis greater or equal to the deque's current length, this has no effect.Examples
# use VecDeque; let mut buf = new; buf.push_front; buf.push_front; buf.push_front; assert_eq!; assert_eq!; buf.truncate_front; assert_eq!;fn allocator(self: &Self) -> &AReturns a reference to the underlying allocator.
fn iter(self: &Self) -> Iter<'_, T>Returns a front-to-back iterator.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; let b: & = &; let c: = buf.iter.collect; assert_eq!;fn iter_mut(self: &mut Self) -> IterMut<'_, T>Returns a front-to-back iterator that returns mutable references.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; for num in buf.iter_mut let b: & = &; assert_eq!;fn as_slices(self: &Self) -> (&[T], &[T])Returns a pair of slices which contain, in order, the contents of the deque.
If
make_contiguouswas previously called, all elements of the deque will be in the first slice and the second slice will be empty. Otherwise, the exact split point depends on implementation details and is not guaranteed.Examples
use VecDeque; let mut deque = new; deque.push_back; deque.push_back; deque.push_back; let expected = ; let = deque.as_slices; assert_eq!; assert_eq!; deque.push_front; deque.push_front; let expected = ; let = deque.as_slices; assert_eq!; assert_eq!;fn as_mut_slices(self: &mut Self) -> (&mut [T], &mut [T])Returns a pair of slices which contain, in order, the contents of the deque.
If
make_contiguouswas previously called, all elements of the deque will be in the first slice and the second slice will be empty. Otherwise, the exact split point depends on implementation details and is not guaranteed.Examples
use VecDeque; let mut deque = new; deque.push_back; deque.push_back; deque.push_front; deque.push_front; // Since the split point is not guaranteed, we may need to update // either slice. let mut update_nth = ; update_nth; update_nth; let v: = deque.into; assert_eq!;fn len(self: &Self) -> usizeReturns the number of elements in the deque.
Examples
use VecDeque; let mut deque = new; assert_eq!; deque.push_back; assert_eq!;fn is_empty(self: &Self) -> boolReturns
trueif the deque is empty.Examples
use VecDeque; let mut deque = new; assert!; deque.push_front; assert!;fn range<R>(self: &Self, range: R) -> Iter<'_, T> where R: RangeBounds<usize>Creates an iterator that covers the specified range in the deque.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the deque.Examples
use VecDeque; let deque: = .into; let range = deque.range.copied.; assert_eq!; // A full range covers all contents let all = deque.range; assert_eq!;fn range_mut<R>(self: &mut Self, range: R) -> IterMut<'_, T> where R: RangeBounds<usize>Creates an iterator that covers the specified mutable range in the deque.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the deque.Examples
use VecDeque; let mut deque: = .into; for v in deque.range_mut assert_eq!; // A full range covers all contents for v in deque.range_mut assert_eq!;fn drain<R>(self: &mut Self, range: R) -> Drain<'_, T, A> where R: RangeBounds<usize>Removes the specified range from the deque in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.
The returned iterator keeps a mutable borrow on the queue to optimize its implementation.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the deque.Leaking
If the returned iterator goes out of scope without being dropped (due to
mem::forget, for example), the deque may have lost and leaked elements arbitrarily, including elements outside the range.Examples
use VecDeque; let mut deque: = .into; let drained = deque.drain.; assert_eq!; assert_eq!; // A full range clears all contents, like `clear()` does deque.drain; assert!;fn splice<R, I>(self: &mut Self, range: R, replace_with: I) -> Splice<'_, <I as >::IntoIter, A> where R: RangeBounds<usize>, I: IntoIterator<Item = T>Creates a splicing iterator that replaces the specified range in the deque with the given
replace_withiterator and yields the removed items.replace_withdoes not need to be the same length asrange.rangeis removed even if theSpliceiterator is not consumed before it is dropped.It is unspecified how many elements are removed from the deque if the
Splicevalue is leaked.The input iterator
replace_withis only consumed when theSplicevalue is dropped.This is optimal if:
- The tail (elements in the deque after
range) is empty, - or
replace_withyields fewer or equal elements thanrange's length - or the lower bound of its
size_hint()is exact.
Otherwise, a temporary vector is allocated and the tail is moved twice.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the deque.Examples
# # use VecDeque; let mut v = from; let new = ; let u: = v.splice.collect; assert_eq!; assert_eq!;Using
spliceto insert new items into a vector efficiently at a specific position indicated by an empty range:# # use VecDeque; let mut v = from; let new = ; v.splice; assert_eq!;- The tail (elements in the deque after
fn clear(self: &mut Self)Clears the deque, removing all values.
Examples
use VecDeque; let mut deque = new; deque.push_back; deque.clear; assert!;fn contains(self: &Self, x: &T) -> bool where T: PartialEq<T>Returns
trueif the deque contains an element equal to the given value.This operation is O(n).
Note that if you have a sorted
VecDeque,binary_searchmay be faster.Examples
use VecDeque; let mut deque: = new; deque.push_back; deque.push_back; assert_eq!; assert_eq!;fn front(self: &Self) -> Option<&T>Provides a reference to the front element, or
Noneif the deque is empty.Examples
use VecDeque; let mut d = new; assert_eq!; d.push_back; d.push_back; assert_eq!;fn front_mut(self: &mut Self) -> Option<&mut T>Provides a mutable reference to the front element, or
Noneif the deque is empty.Examples
use VecDeque; let mut d = new; assert_eq!; d.push_back; d.push_back; match d.front_mut assert_eq!;fn back(self: &Self) -> Option<&T>Provides a reference to the back element, or
Noneif the deque is empty.Examples
use VecDeque; let mut d = new; assert_eq!; d.push_back; d.push_back; assert_eq!;fn back_mut(self: &mut Self) -> Option<&mut T>Provides a mutable reference to the back element, or
Noneif the deque is empty.Examples
use VecDeque; let mut d = new; assert_eq!; d.push_back; d.push_back; match d.back_mut assert_eq!;fn pop_front(self: &mut Self) -> Option<T>Removes the first element and returns it, or
Noneif the deque is empty.Examples
use VecDeque; let mut d = new; d.push_back; d.push_back; assert_eq!; assert_eq!; assert_eq!;fn pop_back(self: &mut Self) -> Option<T>Removes the last element from the deque and returns it, or
Noneif it is empty.Examples
use VecDeque; let mut buf = new; assert_eq!; buf.push_back; buf.push_back; assert_eq!;fn pop_front_if<impl FnOnce(&mut T) -> bool: FnOnce(&mut T) -> bool>(self: &mut Self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>Removes and returns the first element from the deque if the predicate returns
true, orNoneif the predicate returns false or the deque is empty (the predicate will not be called in that case).Examples
use VecDeque; let mut deque: = vec!.into; let pred = ; assert_eq!; assert_eq!; assert_eq!;fn pop_back_if<impl FnOnce(&mut T) -> bool: FnOnce(&mut T) -> bool>(self: &mut Self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>Removes and returns the last element from the deque if the predicate returns
true, orNoneif the predicate returns false or the deque is empty (the predicate will not be called in that case).Examples
use VecDeque; let mut deque: = vec!.into; let pred = ; assert_eq!; assert_eq!; assert_eq!;fn push_front(self: &mut Self, value: T)Prepends an element to the deque.
Examples
use VecDeque; let mut d = new; d.push_front; d.push_front; assert_eq!;fn push_front_mut(self: &mut Self, value: T) -> &mut TPrepends an element to the deque, returning a reference to it.
Examples
use VecDeque; let mut d = from; let x = d.push_front_mut; *x -= 1; assert_eq!;fn push_back(self: &mut Self, value: T)Appends an element to the back of the deque.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; assert_eq!;fn push_back_mut(self: &mut Self, value: T) -> &mut TAppends an element to the back of the deque, returning a reference to it.
Examples
use VecDeque; let mut d = from; let x = d.push_back_mut; *x += 1; assert_eq!;fn prepend<I: IntoIterator<Item = T, IntoIter: DoubleEndedIterator>>(self: &mut Self, other: I)Prepends all contents of the iterator to the front of the deque. The order of the contents is preserved.
To get behavior like [
append][VecDeque::append] where elements are moved from the other collection to this one, useself.prepend(other.drain(..)).Examples
use VecDeque; let mut deque = from; deque.prepend; assert_eq!;Move values between collections like [
append][VecDeque::append] does but prepend to the front:use VecDeque; let mut deque1 = from; let mut deque2 = from; deque1.prepend; assert_eq!; assert!;fn extend_front<I: IntoIterator<Item = T>>(self: &mut Self, iter: I)Prepends all contents of the iterator to the front of the deque, as if [
push_front][VecDeque::push_front] was called repeatedly with the values yielded by the iterator.Examples
use VecDeque; let mut deque = from; deque.extend_front; assert_eq!;This behaves like [
push_front][VecDeque::push_front] was called repeatedly:use VecDeque; let mut deque = from; for v in assert_eq!;fn swap_remove_front(self: &mut Self, index: usize) -> Option<T>Removes an element from anywhere in the deque and returns it, replacing it with the first element.
This does not preserve ordering, but is O(1).
Returns
Noneifindexis out of bounds.Element at index 0 is the front of the queue.
Examples
use VecDeque; let mut buf = new; assert_eq!; buf.push_back; buf.push_back; buf.push_back; assert_eq!; assert_eq!; assert_eq!;fn swap_remove_back(self: &mut Self, index: usize) -> Option<T>Removes an element from anywhere in the deque and returns it, replacing it with the last element.
This does not preserve ordering, but is O(1).
Returns
Noneifindexis out of bounds.Element at index 0 is the front of the queue.
Examples
use VecDeque; let mut buf = new; assert_eq!; buf.push_back; buf.push_back; buf.push_back; assert_eq!; assert_eq!; assert_eq!;fn insert(self: &mut Self, index: usize, value: T)Inserts an element at
indexwithin the deque, shifting all elements with indices greater than or equal toindextowards the back.Element at index 0 is the front of the queue.
Panics
Panics if
indexis strictly greater than the deque's length.Examples
use VecDeque; let mut vec_deque = new; vec_deque.push_back; vec_deque.push_back; vec_deque.push_back; assert_eq!; vec_deque.insert; assert_eq!; vec_deque.insert; assert_eq!;fn insert_mut(self: &mut Self, index: usize, value: T) -> &mut TInserts an element at
indexwithin the deque, shifting all elements with indices greater than or equal toindextowards the back, and returning a reference to it.Element at index 0 is the front of the queue.
Panics
Panics if
indexis strictly greater than the deque's length.Examples
use VecDeque; let mut vec_deque = from; let x = vec_deque.insert_mut; *x += 7; assert_eq!;fn remove(self: &mut Self, index: usize) -> Option<T>Removes and returns the element at
indexfrom the deque. Whichever end is closer to the removal point will be moved to make room, and all the affected elements will be moved to new positions. ReturnsNoneifindexis out of bounds.Element at index 0 is the front of the queue.
Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; assert_eq!; assert_eq!; assert_eq!;fn split_off(self: &mut Self, at: usize) -> Self where A: CloneSplits the deque into two at the given index.
Returns a newly allocated
VecDeque.selfcontains elements[0, at), and the returned deque contains elements[at, len).Note that the capacity of
selfdoes not change.Element at index 0 is the front of the queue.
Panics
Panics if
at > len.Examples
use VecDeque; let mut buf: = .into; let buf2 = buf.split_off; assert_eq!; assert_eq!;fn append(self: &mut Self, other: &mut Self)Moves all the elements of
otherintoself, leavingotherempty.Panics
Panics if the new number of elements in self overflows a
usize.Examples
use VecDeque; let mut buf: = .into; let mut buf2: = .into; buf.append; assert_eq!; assert_eq!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(&T) -> boolRetains only the elements specified by the predicate.
In other words, remove all elements
efor whichf(&e)returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.Examples
use VecDeque; let mut buf = new; buf.extend; buf.retain; assert_eq!;Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
use VecDeque; let mut buf = new; buf.extend; let keep = ; let mut iter = keep.iter; buf.retain; assert_eq!;fn retain_mut<F>(self: &mut Self, f: F) where F: FnMut(&mut T) -> boolRetains only the elements specified by the predicate.
In other words, remove all elements
efor whichf(&mut e)returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.Examples
use VecDeque; let mut buf = new; buf.extend; buf.retain_mut; assert_eq!;fn resize_with<impl FnMut() -> T: FnMut() -> T>(self: &mut Self, new_len: usize, generator: impl FnMut() -> T)Modifies the deque in-place so that
len()is equal tonew_len, either by removing excess elements from the back or by appending elements generated by callinggeneratorto the back.Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; assert_eq!; buf.resize_with; assert_eq!; buf.resize_with; assert_eq!; let mut state = 100; buf.resize_with; assert_eq!;fn make_contiguous(self: &mut Self) -> &mut [T]Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned.
This method does not allocate and does not change the order of the inserted elements. As it returns a mutable slice, this can be used to sort a deque.
Once the internal storage is contiguous, the
as_slicesandas_mut_slicesmethods will return the entire contents of the deque in a single slice.Examples
Sorting the content of a deque.
use VecDeque; let mut buf = with_capacity; buf.push_back; buf.push_back; buf.push_front; // sorting the deque buf.make_contiguous.sort; assert_eq!; // sorting it in reverse order buf.make_contiguous.sort_by; assert_eq!;Getting immutable access to the contiguous slice.
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_front; buf.make_contiguous; if let = buf.as_slicesfn rotate_left(self: &mut Self, n: usize)Rotates the double-ended queue
nplaces to the left.Equivalently,
- Rotates item
ninto the first position. - Pops the first
nitems and pushes them to the end. - Rotates
len() - nplaces to the right.
Panics
If
nis greater thanlen(). Note thatn == len()does not panic and is a no-op rotation.Complexity
Takes
*O*(min(n, len() - n))time and no extra space.Examples
use VecDeque; let mut buf: = .collect; buf.rotate_left; assert_eq!; for i in 1..10 assert_eq!;- Rotates item
fn rotate_right(self: &mut Self, n: usize)Rotates the double-ended queue
nplaces to the right.Equivalently,
- Rotates the first item into position
n. - Pops the last
nitems and pushes them to the front. - Rotates
len() - nplaces to the left.
Panics
If
nis greater thanlen(). Note thatn == len()does not panic and is a no-op rotation.Complexity
Takes
*O*(min(n, len() - n))time and no extra space.Examples
use VecDeque; let mut buf: = .collect; buf.rotate_right; assert_eq!; for i in 1..10 assert_eq!;- Rotates the first item into position
fn binary_search(self: &Self, x: &T) -> Result<usize, usize> where T: OrdBinary searches this
VecDequefor a given element. If theVecDequeis not sorted, the returned result is unspecified and meaningless.If the value is found then
Result::Okis returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found thenResult::Erris returned, containing the index where a matching element could be inserted while maintaining sorted order.See also
binary_search_by,binary_search_by_key, andpartition_point.Examples
Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in
[1, 4].use VecDeque; let deque: = .into; assert_eq!; assert_eq!; assert_eq!; let r = deque.binary_search; assert!;If you want to insert an item to a sorted deque, while maintaining sort order, consider using
partition_point:use VecDeque; let mut deque: = .into; let num = 42; let idx = deque.partition_point; // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` may allow `insert` // to shift less elements. deque.insert; assert_eq!;fn binary_search_by<'a, F>(self: &'a Self, f: F) -> Result<usize, usize> where F: FnMut(&'a T) -> OrderingBinary searches this
VecDequewith a comparator function.The comparator function should return an order code that indicates whether its argument is
Less,EqualorGreaterthe desired target. If theVecDequeis not sorted or if the comparator function does not implement an order consistent with the sort order of the underlyingVecDeque, the returned result is unspecified and meaningless.If the value is found then
Result::Okis returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found thenResult::Erris returned, containing the index where a matching element could be inserted while maintaining sorted order.See also
binary_search,binary_search_by_key, andpartition_point.Examples
Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in
[1, 4].use VecDeque; let deque: = .into; assert_eq!; assert_eq!; assert_eq!; let r = deque.binary_search_by; assert!;fn binary_search_by_key<'a, B, F>(self: &'a Self, b: &B, f: F) -> Result<usize, usize> where F: FnMut(&'a T) -> B, B: OrdBinary searches this
VecDequewith a key extraction function.Assumes that the deque is sorted by the key, for instance with
make_contiguous().sort_by_key()using the same key extraction function. If the deque is not sorted by the key, the returned result is unspecified and meaningless.If the value is found then
Result::Okis returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found thenResult::Erris returned, containing the index where a matching element could be inserted while maintaining sorted order.See also
binary_search,binary_search_by, andpartition_point.Examples
Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in
[1, 4].use VecDeque; let deque: = .into; assert_eq!; assert_eq!; assert_eq!; let r = deque.binary_search_by_key; assert!;fn partition_point<P>(self: &Self, pred: P) -> usize where P: FnMut(&T) -> boolReturns the index of the partition point according to the given predicate (the index of the first element of the second partition).
The deque is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the deque and all elements for which the predicate returns false are at the end. For example,
[7, 15, 3, 5, 4, 12, 6]is partitioned under the predicatex % 2 != 0(all odd numbers are at the start, all even at the end).If the deque is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.
See also
binary_search,binary_search_by, andbinary_search_by_key.Examples
use VecDeque; let deque: = .into; let i = deque.partition_point; assert_eq!; assert!; assert!;If you want to insert an item to a sorted deque, while maintaining sort order:
use VecDeque; let mut deque: = .into; let num = 42; let idx = deque.partition_point; deque.insert; assert_eq!;
impl<T, A: Allocator> VecDeque<T, A>
fn extract_if<F, R>(self: &mut Self, range: R, filter: F) -> ExtractIf<'_, T, F, A> where F: FnMut(&mut T) -> bool, R: RangeBounds<usize>Creates an iterator which uses a closure to determine if an element in the range should be removed.
If the closure returns
true, the element is removed from the deque and yielded. If the closure returnsfalse, or panics, the element remains in the deque and will not be yielded.Only elements that fall in the provided range are considered for extraction, but any elements after the range will still have to be moved if any element has been extracted.
If the returned
ExtractIfis not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Useextract_if().for_each(drop)if you do not need the returned iterator, orretain_mutwith a negated predicate if you also do not need to restrict the range.Using this method is equivalent to the following code:
# use VecDeque; # let some_predicate = ; # let mut deq: = .collect; # let mut deq2 = deq.clone; # let range = 1..5; let mut i = range.start; let end_items = deq.len - range.end; # let mut extracted = vec!; while i < deq.len - end_items # let extracted2: = deq2.extract_if.collect; # assert_eq!; # assert_eq!;But
extract_ifis easier to use.extract_ifis also more efficient, because it can backshift the elements of the array in bulk.The iterator also lets you mutate the value of each element in the closure, regardless of whether you choose to keep or remove it.
Panics
If
rangeis out of bounds.Examples
Splitting a deque into even and odd values, reusing the original deque:
use VecDeque; let mut numbers = from; let evens = numbers.extract_if.; let odds = numbers; assert_eq!; assert_eq!;Using the range argument to only process a part of the deque:
use VecDeque; let mut items = from; let ones = items.extract_if.; assert_eq!; assert_eq!;
impl<T: Clone, A: Allocator> VecDeque<T, A>
fn resize(self: &mut Self, new_len: usize, value: T)Modifies the deque in-place so that
len()is equal to new_len, either by removing excess elements from the back or by appending clones ofvalueto the back.Examples
use VecDeque; let mut buf = new; buf.push_back; buf.push_back; buf.push_back; assert_eq!; buf.resize; assert_eq!; buf.resize; assert_eq!;fn extend_from_within<R>(self: &mut Self, src: R) where R: RangeBounds<usize>Clones the elements at the range
srcand appends them to the end.Panics
Panics if the starting index is greater than the end index or if either index is greater than the length of the vector.
Examples
use VecDeque; let mut characters = from; characters.extend_from_within; assert_eq!; let mut numbers = from; numbers.extend_from_within; assert_eq!; let mut strings = from; strings.extend_from_within; assert_eq!;fn prepend_from_within<R>(self: &mut Self, src: R) where R: RangeBounds<usize>Clones the elements at the range
srcand prepends them to the front.Panics
Panics if the starting index is greater than the end index or if either index is greater than the length of the vector.
Examples
use VecDeque; let mut characters = from; characters.prepend_from_within; assert_eq!; let mut numbers = from; numbers.prepend_from_within; assert_eq!; let mut strings = from; strings.prepend_from_within; assert_eq!;
impl<'a, T: 'a + Copy, A: Allocator> Extend for VecDeque<T, A>
fn extend<I: IntoIterator<Item = &'a T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, elem: &'a T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T> Any for VecDeque<T, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for VecDeque<T, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for VecDeque<T, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for VecDeque<T, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Default for VecDeque<T>
fn default() -> VecDeque<T>Creates an empty deque.
impl<T> From for VecDeque<T, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> FromIterator for VecDeque<T>
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T>
impl<T> ToOwned for VecDeque<T, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, A> Freeze for VecDeque<T, A>
impl<T, A> RefUnwindSafe for VecDeque<T, A>
impl<T, A> Send for VecDeque<T, A>
impl<T, A> Sync for VecDeque<T, A>
impl<T, A> Unpin for VecDeque<T, A>
impl<T, A> UnwindSafe for VecDeque<T, A>
impl<T, A: Allocator> Drop for VecDeque<T, A>
fn drop(self: &mut Self)
impl<T, A: Allocator> Extend for VecDeque<T, A>
fn extend<I: IntoIterator<Item = T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, elem: T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T, A: Allocator> From for VecDeque<T, A>
fn from(other: Vec<T, A>) -> SelfTurn a
Vec<T>into aVecDeque<T>.This conversion is guaranteed to run in O(1) time and to not re-allocate the
Vec's buffer or allocate any additional memory.
impl<T, A: Allocator> Index for VecDeque<T, A>
fn index(self: &Self, index: usize) -> &T
impl<T, A: Allocator> IndexMut for VecDeque<T, A>
fn index_mut(self: &mut Self, index: usize) -> &mut T
impl<T, A: Allocator> IntoIterator for VecDeque<T, A>
fn into_iter(self: Self) -> IntoIter<T, A>Consumes the deque into a front-to-back iterator yielding elements by value.
impl<T, N: usize> From for VecDeque<T>
fn from(arr: [T; N]) -> SelfConverts a
[T; N]into aVecDeque<T>.use VecDeque; let deq1 = from; let deq2: = .into; assert_eq!;
impl<T, U> Into for VecDeque<T, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for VecDeque<T, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for VecDeque<T, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T, U, A: Allocator> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &&mut [U]) -> bool
impl<T, U, A: Allocator> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &Vec<U, A>) -> bool
impl<T, U, A: Allocator> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &&[U]) -> bool
impl<T, U, A: Allocator, N: usize> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &[U; N]) -> bool
impl<T, U, A: Allocator, N: usize> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &&[U; N]) -> bool
impl<T, U, A: Allocator, N: usize> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &&mut [U; N]) -> bool
impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Overwrites the contents of
selfwith a clone of the contents ofsource.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.
impl<T: Eq, A: Allocator> Eq for VecDeque<T, A>
impl<T: Hash, A: Allocator> Hash for VecDeque<T, A>
fn hash<H: Hasher>(self: &Self, state: &mut H)
impl<T: Ord, A: Allocator> Ord for VecDeque<T, A>
fn cmp(self: &Self, other: &Self) -> Ordering
impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A>
fn eq(self: &Self, other: &Self) -> bool
impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A>
fn partial_cmp(self: &Self, other: &Self) -> Option<Ordering>
impl<T: fmt::Debug, A: Allocator> Debug for VecDeque<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result