bhylu.com

Advertisements

C++ List

Erase one linked-list node through its iterator and understand the cost of finding that node.

How it works

std::list owns a doubly linked sequence. Given a valid iterator, insertion and erasure can relink nodes without shifting every element. Finding an arbitrary position still requires traversal; there is no random-access subscript. Node allocation and poor locality can make a vector faster for many small workloads. Use a list only when stable-node or splicing requirements justify it. Erasure invalidates references and iterators to the erased element, even when other nodes remain stable.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror lists.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · lists.cpp

#include <iostream>
#include <list>
#include <string>

int main() {
    std::list<std::string> stops{"Gate", "Cancelled", "Quay"};
    auto position = stops.begin();
    ++position;
    position = stops.erase(position);
    std::cout << "Following: " << *position << '\n';
    std::cout << "Remaining: " << stops.size() << '\n';
}

Expected result

Following: Quay
Remaining: 2

The fixture advances to an existing middle node. erase returns the following iterator, which is dereferenceable here because Quay follows it. If the erased node were last, the returned iterator would equal end. forward_list offers a singly linked alternative with a different before-position API; do not assume list operations transfer unchanged.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.