TExcelTAD
Home › C++ › C++ List

C++ List

std::list is a doubly linked list. Each element lives in its own node, and every node stores pointers to the previous and next node. That design gives the list a different set of strengths and weaknesses than vector.

std::vector std::list
Memory layout one contiguous block separate nodes linked by pointers
Access by index (v[5]) instant not available — walk from one end
Insert/erase at the front slow (shift everything) instant
Insert/erase in the middle (with an iterator) slow instant
Iterators stay valid after insert/erase often not yes (except for the erased element)
Cache friendliness excellent poor

Creating and modifying a list

Include <list>. You can add and remove at both ends:

cpp · try it yourself
#include <iostream>
#include <list>
#include <string>
using namespace std;

void print(const list<string>& l) {
    for (const auto& s : l) cout << s << " ";
    cout << "(size " << l.size() << ")\n";
}

int main() {
    list<string> queue = {"bob", "carol"};
    queue.push_back("dave");
    queue.push_front("alice");
    print(queue);

    cout << "front: " << queue.front() << ", back: " << queue.back() << "\n";

    queue.pop_front();
    queue.pop_back();
    print(queue);
}
alice bob carol dave (size 4)
front: alice, back: dave
bob carol (size 2)

There is no operator[] — a list cannot jump to "element number 3" without walking there.

Inserting and erasing with iterators

To work in the middle of a list you use iterators (positions). insert adds before the iterator; erase removes the element and returns an iterator to the next one:

cpp · try it yourself
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> nums = {1, 2, 3, 4, 5, 6};

    auto it = nums.begin();
    advance(it, 2);                 // move to the third element (3)
    nums.insert(it, 99);            // insert before 3

    // remove all even numbers while iterating
    for (auto i = nums.begin(); i != nums.end(); ) {
        if (*i % 2 == 0) {
            i = nums.erase(i);      // erase returns the next position
        } else {
            ++i;
        }
    }

    for (int n : nums) cout << n << " ";
    cout << "\n";
}
1 99 3 5

List-specific operations

Because lists cannot use the general std::sort (it needs random access), they come with their own member functions — and some of them, like splice, are only possible with linked nodes:

cpp · try it yourself
#include <iostream>
#include <list>
using namespace std;

void print(const char* label, const list<int>& l) {
    cout << label;
    for (int n : l) cout << n << " ";
    cout << "\n";
}

int main() {
    list<int> a = {5, 1, 4, 1, 3};
    list<int> b = {9, 2, 7};

    a.sort();                      print("sorted a:   ", a);
    a.unique();                    print("unique a:   ", a);
    a.remove(4);                   print("remove 4:   ", a);
    a.reverse();                   print("reversed a: ", a);

    b.sort();
    a.sort();
    a.merge(b);                    // merges two sorted lists; b becomes empty
    print("merged:     ", a);
    cout << "b size: " << b.size() << "\n";

    list<int> c = {100, 200};
    a.splice(a.begin(), c);        // move all nodes of c to the front of a, no copying
    print("spliced:    ", a);
}
sorted a:   1 1 3 4 5
unique a:   1 3 4 5
remove 4:   1 3 5
reversed a: 5 3 1
merged:     1 2 3 5 7 9
b size: 0
spliced:    100 200 1 2 3 5 7 9
Member Effect
sort() sorts the list
unique() removes consecutive duplicates
remove(x) / remove_if(pred) removes matching elements
reverse() reverses the order
merge(other) merges another sorted list into this one
splice(pos, other) moves nodes from another list, without copying

When to use list

In practice vector is faster than list for most workloads, even with insertions in the middle, because modern CPUs love contiguous memory. Reach for list when you need stable iterators (other code holds positions that must stay valid), frequent splice operations, or insertion/removal in the middle of very large sequences of big objects.

Tip: There is also std::forward_list, a singly linked list that uses less memory but can only be traversed forwards.

Test yourself

Which operation does std::list NOT support?

  1. push_front
  2. push_back
  3. operator[]
  4. insert with an iterator

Why does std::list have its own sort() member?

  1. It sorts faster than vector
  2. std::sort requires random-access iterators
  3. Lists are always sorted
  4. For backwards compatibility only

What does l.erase(it) return?

  1. Nothing
  2. The erased value
  3. An iterator to the element after the erased one
  4. The new size