List<T>

cer::List<T> represents a dynamically-sized array, just like std::vector<T>. It ensures that its items are laid out in contiguous storage.

The signature of List is as follows:

template <typename T, int InlineCapacity = ...>
class List;

List offers a similar API to std::vector and is supported by <algorithm> functions. There are some differences however.


Operations

Construction

auto list1 = List<int>();
auto list2 = List { 1, 2, 3 };
auto list3 = List<int> { 1, 2, 3 };

Adding elements

Adding elements to the end of the list is done by using the add() method, instead of push_back(). Appending other lists and ranges is done by using the append() method.

auto list = List<int>();

list.add(1);            // = [1]
list.add(2);            // = [1, 2]
list.append({1, 2, 3}); // = [1, 2, 1, 2, 3]

auto list2 = List { -1, -2 };
list.append(list2);     // = [1, 2, 1, 2, 3, -1, -2]

Finding elements

For convenience, a List provides quick access methods, so that you don’t have to work with std::find() and iterators. Instead, these methods return a simple boolean and Option values.

contains() and indexOf()
auto list = List { 1, 2, 3 };

if (list.contains(3)) {
    // ...
}

auto idx = list.indexOf(2); // = 1
indexOfIf()
// Get the index of the first value that satisfies a condition.
// idx1 is of type Option<int> and will have a value of 2 (the index of 3).
auto idx1 = list.indexOfIf([](int value) {
    return value > 2;
});

// idx2 is of type Option<int> and will be empty.
auto idx2 = list.indexOfIf([](int value) {
    return value > 100;
});
isEmpty()
// Simply checks if the list is empty.
if (list.isEmpty()) {
    // ...
}

Small buffer optimization

List implements a small buffer optimization, which means that it’s able to store an arbitrary number of elements on the stack instead of on the heap.

The capacity for this small buffer is specified using the second template parameter (InlineCapacity), and is expected to be a positive int.

This allows you to avoid heap allocations when you can estimate the number of items that will be in stored in a list, in the average case.

Example
auto list = List<int, 3>();
list.add(1); // Storage is on stack
list.add(2); // Storage is on stack
list.add(3); // Storage is on stack
list.add(4); // Storage moved to heap

Calling clear() will not move the storage back to the stack.