Top Qs
Timeline
Chat
Perspective

Sequence container (C++)

Group of standard library class templates From Wikipedia, the free encyclopedia

Remove ads

In computing, sequence containers refer to a group of container class templates in the standard library of the C++ programming language 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: array, vector, inplace_vector, list, forward_list, deque, and hive. Each of these containers implements different algorithms for data storage, which means that they have different speed guarantees for different operations:[1]

  • array implements a compile-time non-resizable array.
  • vector implements an array with fast random access and an ability to automatically resize when appending elements.
  • inplace_vector implements a resizable array with contiguous in-place storage.
  • deque implements a double-ended queue with comparatively fast random access.
  • list implements a doubly linked list.
  • forward_list implements a singly linked list.
  • hive implements an object pool.

Since each of the containers needs to be able to copy its elements in order to function properly, the type of the elements must fulfill CopyConstructible and Assignable requirements.[2] 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.

Remove ads

History

Originally, only vector, list and deque were defined. Until the standardization of the C++ language in 1998, they were part of the Standard Template Library (STL), 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.[3]

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. 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++26, two new sequence containers were added: inplace_vector and hive.

Remove ads

Properties

Summarize
Perspective

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<T> (where T is the stored type).

Array

std::array<T, N> implements a non-resizable array. The size is 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 essentially equivalent to core-language arrays such as T[] in Java or [T; N] in Rust. Traditional C arrays (T[]) 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.

using std::array;

array<int, 3> a = {1, 2, 3}; // OK
array<int> a = {1, 2, 3}; // not OK

// compare with C-style arrays:
int a[3] = {1, 2, 3}; // OK
int a[] = {1, 2, 3}; // 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.

Vectors

Vector

The elements of a std::vector<T> are stored contiguously.[4] 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 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 (by array indices). 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 (other than, perhaps, at the end) 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,[1] 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.[1][5] 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.[6] Using an invalidated reference causes undefined behaviour.

The reserve() operation may be used to prevent unnecessary reallocations. After a call to reserve(n), the vector's capacity is guaranteed to be at least n.[7]

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.[8]

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 the vector 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.[9] This is widely considered a mistake.[10][11] vector<bool> does not meet the requirements for a C++ Standard Library container. For instance, a Container<T>::reference must be a true lvalue of type T. This is not the case with vector<bool>::reference, which is a proxy class convertible to bool.[12] Similarly, the vector<bool>::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<bool> should be deprecated and subsequently removed from the standard library, while the functionality will be reintroduced under a different name.[13]

If looking to store a list of bool whose size is known at compile time, a std::bitset<N> (bit array) is the more reasonable collection to use, however bitset unlike vector is not dynamic.

In-place vector

std::inplace_vector<T, N> is a dynamically-resizable array with contiguous in-place storage.

Deque

std::deque<T> 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 essentially equivalent to java.util.Deque in Java or std::collections::VecDeque in Rust.

Linked lists

Doubly linked list

The std::list<T> 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 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 ( operation). 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 (such as ints) the memory overhead is much more significant than that of a vector. Each node (of type T takes up sizeof(T) + 2 * sizeof(T*). Pointers are typically one word (usually four bytes under 32-bit operating systems), 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

The std::forward_list<T> data structure implements a singly linked list.

Few languages have a distinct singly linked list type like forward_list, however external libraries such as fwdlist for Rust exist.[14]

Hive

std::hive<T> 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.

Remove ads

Overview of functions

Summarize
Perspective

The containers are defined in headers named after the names of the containers, e.g. vector is defined in header <vector>. All containers satisfy the requirements of the Container concept, which means they have begin(), end(), size(), max_size(), empty(), and swap() methods.

Member functions

More information Functions, array (C++11) ...

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 (Algorithm (C++)) that can be used with the list and forward_list class:

Operations

Non-member functions

Remove ads

Usage example

Summarize
Perspective

The following example demonstrates various techniques involving a vector and C++ Standard Library algorithms (with C++20 std::ranges), 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() {
    array<int, 4> arr{ 1, 2, 3, 4 };

    // initialize a vector from an array
    vector<int> numbers(arr.cbegin(), arr.cend());

    // insert more numbers into the vector
    numbers.push_back(5);
    numbers.push_back(6);
    numbers.push_back(7);
    numbers.push_back(8);
    // the vector currently holds { 1, 2, 3, 4, 5, 6, 7, 8 }

    // randomly shuffle the elements
    random_device rd; // Seed for the random number generator
    mt19937 g(rd()); // Mersenne Twister random number engine
    std::ranges::shuffle(numbers, g);

    // locate the largest element, O(n)
    int largest = std::ranges::max_element(numbers);
    int indexOfLargest = std::ranges::distance(numbers.cbegin(), largest);

    std::println("The largest number is {}, located at index {}", largest, indexOfLargest);

    // sort the elements
    std::ranges::sort(numbers);

    // find the position of the number 5 in the vector 
    int five = std::ranges::lower_bound(numbers, 5);
    int indexOfFive = std::ranges::distance(numbers.cbegin(), five);

    std::println("The number 5 is located at index {}", indexOfFive);

    // erase all the elements greater than 4   
    numbers.erase(
        std::ranges::remove_if(
            numbers,
            [](int n) constexpr -> bool { return n > 4; }
        ),
        numbers.end()
    );

    // print all the remaining numbers
    for (int element : numbers) {
        std::print("{}", element);
    }
}

The output will be the following:

The largest number is 8
It is located at index 6 (implementation-dependent)
The number 5 is located at index 4
1 2 3 4
Remove ads

References

  • William Ford, William Topp. Data Structures with C++ and STL, Second Edition. Prentice Hall, 2002. ISBN 0-13-085850-1. Chapter 4: The Vector Class, pp. 195203.
  • Josuttis, Nicolai M. (1999). The C++ Standard Library. Addison-Wesley. ISBN 0-201-37926-0.

Notes

Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads