Site Tools


wiki:hpp-forward-list

Table of Contents

<forward_list>

<forward_list> is a singly-linked list: fast insertion and deletion at the front (O(1)), but no random access and reverse iteration. It uses less memory than std::list and can be faster in practice due to better cache locality.

Use it when you need a linked list and only iterate forward; otherwise prefer std::vector.

Example

This example demonstrates efficient push and pop operations at the front of a forward list.

// compile: g++ -std=c++11 -o forwardlistexample forwardlistexample.cpp
// run: ./forwardlistexample
// description: forward_list operations
 
#include <forward_list>
#include <iostream>
 
int main() {
    std::forward_list<int> fl = {1, 2, 3};
 
    fl.push_front(0);
    std::cout << "after push_front(0): ";
    for (int x : fl) std::cout << x << " ";
    std::cout << "\n";
 
    fl.pop_front();
    std::cout << "after pop_front: ";
    for (int x : fl) std::cout << x << " ";
    std::cout << "\n";
 
    return 0;
}
wiki/hpp-forward-list.md · Last modified: by 127.0.0.1