Sequence container (C++)
In C++, sequence containers or sequence collections refer to a group of container class templates in the standard library that implement storage of data elements. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. One common property of all sequential containers is that the elements can be accessed sequentially. Like all other standard library components, they reside in namespace
std.The following containers are defined in the current revision of the C++ standard:
std::arrayimplements a compile-time non-resizable array.std::bitsetimplements a compile-time bit set.std::vectorimplements an array with fast random access and an ability to automatically resize when appending elements.std::inplace_vectorimplements a resizable array with contiguous in-place storage.std::dequeimplements a double-ended queue with comparatively fast random access.std::listimplements a doubly linked list.std::forward_listimplements a singly linked list.std::hiveimplements an object pool.
There are also versions of these collections in namespace
std::pmr. These versions specify the optional template parameter Allocator as std::pmr::polymorphic_allocator.C++ further defines container adapters that wrap a sequence container:
std::stackimplements a stack withdequeas the default underlying container.std::queueimplements a queue withdequeas the default underlying container.std::priority_queueimplements a priority queue withvectoras the default underlying container.std::flat_setimplements a "flat set" withvectoras the default underlying container.std::flat_mapimplements a "flat map" withvectoras the default underlying containers.std::flat_multisetimplements a "flat multi-set" withvectoras the default underlying container.std::flat_multimapimplements a "flat multi-map" withvectoras the default underlying containers.
std::vector as the underlying container, unlike their "non-flat" equivalents, which store data as red–black trees.View container types represent views over non-owning arrays of elements:
std::spanimplements a non-owning view over a contiguous sequence of objects.std::mdspanimplements a non-owning view over a multi-dimensional array.
CopyConstructible and Assignable requirements.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.1 Container requirements para. 4 For a given container, all elements must belong to the same type. For instance, one cannot store data in the form of both char and int within the same container instance.History
Originally, onlyvector, list and deque were defined. Until the standardization of the C++ language in 1998, they were part of the Standard Template Library, published by SGI. Alexander Stepanov, the primary designer of the STL, bemoans the choice of the name vector, saying that it comes from the older programming languages Scheme and Lisp but is inconsistent with the mathematical meaning of the term.The
array container at first appeared in several books under various names. Later it was incorporated into a Boost library, and was proposed for inclusion in the standard C++ library. The motivation for inclusion of array was that it solves two problems of the C-style array: the lack of an STL-like interface, and an inability to be copied like any other object. However, unlike C-style arrays, it can only be declared at compile-time, and not at runtime. It firstly appeared in C++ TR1 and later was incorporated into C++11.The
forward_list container was added to C++11 as a space-efficient alternative to list when reverse iteration is not needed.In C++20, the class
std::formatter was introduced for specifying how a class should be formatted when passed to std::format or std::print. This added formatting for various collection types.In C++26, two new sequence containers were added:
inplace_vector and hive.Properties
array, vector and deque all support fast random access to the elements. list supports bidirectional iteration, whereas forward_list supports only unidirectional iteration.array does not support element insertion or removal. vector supports fast element insertion or removal at the end. Any insertion or removal of an element not at the end of the vector needs elements between the insertion position and the end of the vector to be copied. The iterators to the affected elements are thus invalidated. In fact, any insertion can potentially invalidate all iterators. Also, if the allocated storage in the vector is too small to insert elements, a new array is allocated, all elements are copied or moved to the new array, and the old array is freed. deque, list and forward_list all support fast insertion or removal of elements anywhere in the container. list and forward_list preserves validity of iterators on such operation, whereas deque invalidates all of them.The collections
vector, deque, list and forward_list also have a template parameter Allocator which is default-specified as std::allocator.Containers
Array
std::array implements a non-resizable array. The size N, an unsigned integer, must be determined at compile-time by a template parameter. By design, the container does not support allocators because it is basically a C-style array wrapper. C++ does not support variable-length arrays.It is declared in header
.It is essentially equivalent to core-language arrays such as
T in Java or in Rust. Traditional C arrays do not store information such as length. array, unlike T, must always specify its size at declaration, be inferred by the compiler. This is similar to another collection, std::bitset, which acts as a bit array whose size must be known at compile time.import std;
using std::array;
array
array
array a; // OK: deduces type as array
// compare with C-style arrays:
int a = ; // OK
int a = ; // OK
std::span is a close relative of array, for non-owning array views. std::mdspan is a multi-dimensional version of span, however these are view containers.Bit set
std::bitset implements a non-resizable bit set. The size N, an unsigned integer, must be determined at compile time as a template parameter, much like std::array. It is much more compact than std::vector, storing just bits and a small amount of padding.It further supports bitwise operations, as well as accessing and modifying specific bits. It supports conversion to
unsigned long as well as to strings, and testing/querying the number of active bits. However, unlike other containers, it does not support iterators.It is declared in header
.It is essentially equivalent to
java.util.BitSet in Java, or the former std::collections::BitSet in Rust.For a dynamic bit set, third party libraries such as Boost provide classes such as
boost::dynamic_bitset. While vector does store packed bits and can be dynamically sized, vector::operator returns a proxy type vector::reference , and lacks the bitwise operations provided by bitset.Vectors
Vector
The elements of astd::vector are stored contiguously. Like all dynamic array implementations, vectors have low memory usage and good locality of reference and data cache utilization. Unlike other STL containers, such as deques and lists, vectors allow the user to denote an initial capacity for the container.It is declared in header
.It is essentially equivalent to
java.util.ArrayList in Java or std::vec::Vec in Rust.Vectors allow random access; that is, an element of a vector may be referenced in the same manner as elements of arrays. Linked-lists and sets, on the other hand, do not support random access or pointer arithmetic.
The vector data structure is able to quickly and easily allocate the necessary memory needed for specific data storage, and it is able to do so in amortized constant time. This is particularly useful for storing data in lists whose length may not be known prior to setting up the list but where removal is rare. Erasing elements from a vector or even clearing the vector entirely does not necessarily free any of the memory associated with that element.
Capacity and reallocation
A typical vector implementation consists, internally, of a pointer to a dynamically allocated array, and possibly data members holding the capacity and size of the vector. The size of the vector refers to the actual number of elements, while the capacity refers to the size of the internal array.When new elements are inserted, if the new size of the vector becomes larger than its capacity, reallocation occurs.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.3 vector modifiers para. 1 This typically causes the vector to allocate a new region of storage, move the previously held elements to the new region of storage, and free the old region.
Because the addresses of the elements change during this process, any references or iterators to elements in the vector become invalidated.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.2 vector capacity para. 5 Using an invalidated reference causes undefined behaviour.
The reserve operation may be used to prevent unnecessary reallocations. After a call to reserve, the vector's capacity is guaranteed to be at least n.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.2 vector capacity para. 2
The vector maintains a certain order of its elements, so that when a new element is inserted at the beginning or in the middle of the vector, subsequent elements are moved backwards in terms of their assignment operator or copy constructor. Consequently, references and iterators to elements after the insertion point become invalidated.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.3 vector modifiers para. 3
C++ vectors do not support in-place reallocation of memory, by design; i.e., upon reallocation of a vector, the memory it held will always be copied to a new block of memory using its elements' copy constructor, and then released. This is inefficient for cases where the vector holds plain old data and additional contiguous space beyond the held block of memory is available for allocation.
Specialization for bool
The Standard Library defines a specialization of thevector template for bool. The description of this specialization indicates that the implementation should pack the elements so that every bool only uses one bit of memory.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.5 Class vectorvector can be seen as similar to a dynamic bit set, but while vector does store packed bits and can be dynamically sized, ::operator returns a proxy type vector::reference , and lacks the bitwise operations provided by bitset. This is widely considered a mistake. vector does not meet the requirements for a C++ Standard Library container. For instance, a Container::reference must be a true lvalue of type T. This is not the case with vector::reference , which is a proxy class convertible to bool.ISO/IEC. ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.5 Class vectorvector::iterator does not yield a bool& when dereferenced. There is a general consensus among the C++ Standard Committee and the Library Working Group that vector should be deprecated and subsequently removed from the standard library, while the functionality will be reintroduced under a different name.If looking to store a list of
bool whose size is known at compile time, a std::bitset is the more reasonable collection to use, due to lower overhead and being overall more efficient. However, bitset unlike vector is not dynamic.In-place vector
std::inplace_vector is a dynamically-resizable array with contiguous in-place storage.It is declared in header
.Deque
std::deque is a container class template that implements a double-ended queue. It provides similar computational complexity to vector for most operations, with the notable exception that it provides amortized constant-time insertion and removal from both ends of the element sequence. Unlike vector, deque uses discontiguous blocks of memory, and provides no means to control the capacity of the container and the moment of reallocation of memory. Like vector, deque offers support for random-access iterators, and insertion and removal of elements invalidates all iterators to the deque.It is declared in header
.It is essentially equivalent to
java.util.ArrayDeque in Java or std::collections::VecDeque in Rust.Linked lists
Doubly linked list
Thestd::list data structure implements a doubly linked list. Data is stored non-contiguously in memory which allows the list data structure to avoid the reallocation of memory that can be necessary with vectors when new elements are inserted into the list.It is declared in header
.It is essentially equivalent to
java.util.LinkedList in Java or std::collections::LinkedList in Rust.The list data structure allocates and deallocates memory as needed; therefore, it does not allocate memory that it is not currently using. Memory is freed when an element is removed from the list.
Lists are efficient when inserting new elements in the list; this is an operation. No shifting is required like with vectors.
Lists do not have random-access ability like vectors. Accessing a node in a list is an operation that requires a list traversal to find the node that needs to be accessed.
With small data types the memory overhead is much more significant than that of a vector. Each node + 2 * sizeof. Pointers are typically one word, which means that a list of four byte integers takes up approximately three times as much memory as a vector of integers.
Singly linked list
Thestd::forward_list data structure implements a singly linked list.It is declared in header
.Few languages have a distinct singly linked list type like
forward_list, however external libraries such as fwdlist for Rust exist.Hive
std::hive is a collection that reuses erased elements' memory. It can be seen as similar to an object pool. It uses another class, std::hive_limits to store layout information on block capacity limits. Unlike vector which stores data in a single contiguous block of memory, it stores data in a chain of multiple blocks of memory. It can store and erase elements efficiently, and guarantees iterator stability.Lookup, removal, and iteration are, while insertion is amortised.
It is based on the class
plf::colony from the plf library.It is declared in header
.External libraries such as colony exist for Rust, which implement
Colony.Container adapters
A container adapter in C++ is for wrapping sequence collection types in an alternate interface. Each collection type has a template parameterContainer which is default-specified, but can be configured as needed.Stack
Thestd::stack data structure implements a stack. Its underlying collection type is deque.It is declared in header
.It is essentially equivalent to
java.util.Stack in Java.Queue
Thestd::queue data structure implements a queue. Its underlying collection type is deque.It is declared in header
.It is similar to the Java interface
java.util.Queue.Priority queue
Thestd::priority_queue data structure implements a priority queue, which is by default sorted using function object std::less. Its underlying collection type is vector.It is declared in header
.It is essentially equivalent to
java.util.PriorityQueue in Java, or std::collections::BinaryHeap in Rust.Flat set
Thestd::flat_set data structure implements a "flat set", which stores a collection of unique keys, which is by default sorted using function object std::less. Its underlying collection type is vector.It is declared in header
.Flat map
Thestd::flat_map data structure implements a "flat map", which stores a collection of unique key-value pairs, which is by default sorted using function object std::less. It has two underlying collections, both by default vector.It is declared in header
.Flat multi-set
Thestd::flat_multiset data structure implements a "flat multi-set", which stores a collection of keys, which is by default sorted using function object std::less. It allows for multiple keys with equivalent values. Its underlying collection type is vector.It is declared in header
.Flat multi-map
Thestd::flat_multimap data structure implements a "flat multi-map", which stores a collection of key-value pairs, which is by default sorted using function object std::less. It allows for multiple entries with equivalent keys. It has two underlying collections, both by default vector.It is declared in header
.Views
A view container in C++ is used for interacting with various non-owning arrays of elements.Span
Thestd::span data structure implements a non-owning view over a single-dimensional contiguous sequence of objects.It is declared in header
.It is similar to the [Non-blocking I/O (Java)|] classes
Buffer and its descendants, which are each non-owning views over primitive arrays, in Java, or &, &mut in Rust.Multi-dimensional span
Thestd::mdspan data structure implements a non-owning view over a multi-dimensional array.It is declared in header
.Overview of functions
The containers are defined in headers named after the names of the containers, e.g.vector is defined in header . All containers satisfy the requirements of the concept, which means they have begin, end, size, max_size, empty, and swap methods.Member functions
There are other operations that are available as a part of the list class and there are algorithms that are part of the C++ STL that can be used with thelist and forward_list class:Operations
and- Merges two sorted listsand- Moves elements from another listand- Removes elements equal to the given valueand- Removes elements satisfying specific criteriaand- Reverses the order of the elementsand- Removes consecutive duplicate elementsand- Sorts the elements
Usage example
The following example demonstrates various techniques involving a vector and C++ Standard Library algorithms, notably shuffling, sorting, finding the largest element, and erasing from a vector using the erase-remove idiom.import std;
using std::array;
using std::mt19937;
using std::random_device;
using std::vector;
int main
The output will be the following:
The largest number is 8
It is located at index 6
The number 5 is located at index 4
1 2 3 4