std::collections

This covers the vectors, maps, sets, and binary heaps.

There are four main categories of collection, but for the majority of the time Vec and HashMap should be used.

The collection types are

  • Sequences (VecVecDequeLinkedList - if you're used to C#, these provide the functionality of List<T>)
  • Maps (HashMapBTreeMap. For C# users, these equate roughly to Dictionary<T, U>, and Map)
  • Sets (HashSetBTreeSet)
  • BinaryHeap

Which collection should be used depends on what you want to do. Each will have a performance impact depending on what you're doing, though usually it's only HashMap that will give a negative impact.

Examples of use:

  • VecCreates a collection of type T that can be resized; elements can be added to the end
  • VecDeque: Creates a collection of type T, but with elements insertable at both ends; needs a queue or double-ended queue (deque)
  • LinkedList: Used when you want a Vec or VecDeque, and to split and append lists
  • HashMap: Creates a cached association of keys with values
  • BTreeMap: Use with key-pair values where in general you want the largest and smallest key-pair values
  • BinaryHeap: Stores elements, but only processes the biggest or most important ones when you want them

Each of these collections deals with its own memory handling. This is important as collections are able to allocate more space as required (and within the limitations of the hardware capacity of the machine they are running on).

Consider the following: I create a Vec<T> without setting a capacity. Let T be a structure. This is not an uncommon occurrence. I add a number of objects to the Vec, and each is then allocated on the heap. The heap expands, which is fine. I then delete a number of these objects. Rust then repositions the other members of the heap belonging to the Vec.

If I allocated space using with_capacity, then we have a maximum allocation available, which further helps with memory handling. We can help memory allocation further by using shrink_to_fit, which reduces the size of our Vec to fit the size required.

Iterators

Iterators are very useful and used in libraries. Primarily, an iterator is used in a for loop. Almost all collections provide three iterators: iteriter_mut, and into_iter. Each of the iterator types performs a different function:

  • iter: This provides an iterator of immutable references to all contents of the collection in the order that best suits the collection type.
  • iter_mut: This provides an iterator of mutable references in the same order as iter.
  • into_iter: This transforms the collection into an iterator. Very useful when the collection isn't needed, but its contents are. The into_iter iterator also includes the ability to extend a vector.

StructsBTreeMapBTreeSetBinaryHeapHashMapHashSetLinkedList, and VecDeque.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset