Notes

πŸ“š Detailed Notes: Understanding STL list Container in C++


🧱 What is a list in C++?

Definition:

  • A list in C++ STL is a doubly linked list.

  • Each element (node) contains:

    • The actual value

    • A pointer to the next node

    • A pointer to the previous node

Key Characteristics:

FeatureList (STL)
TypeDoubly Linked List
SizeDynamic
Fast forInsertions & Deletions
Slow forSearching
Memory AllocationNon-contiguous

βš™οΈ How to Use list in C++

1. Include the header

#include <list>

2. Creating a list

std::list<int> myList;

This creates an empty list of integers named myList.


βž• Inserting Elements

Two Common Insertion Methods:

MethodDescriptionExample
push_back()Adds element at the endmyList.push_back(10);
push_front()Adds element at the beginningmyList.push_front(30);

πŸ“€ Printing Elements of the List

Using Iterators:

for (std::list<int>::iterator it = myList.begin(); it != myList.end(); ++it) {
    std::cout << *it << std::endl;
}
  • it is an iterator (like a pointer).

  • *it dereferences the iterator to access the actual value.

  • Iterators are essential for traversing through STL containers.


❌ Deleting Elements

Erasing an Element:

myList.erase(myList.begin()); // Deletes the first element
  • You pass an iterator to the erase() function.

  • Can delete any element if you pass the correct iterator.


πŸ•ΉοΈ Real-World Example: Matchmaking System in Games

Imagine a Battle Royale game lobby (like Fortnite, PUBG, Warzone) where:

  • Players have a skill rating (1–10)

  • You want to match similar skilled players to make it fair

1. Setup

std::list<int> allPlayers = {2, 9, 6, 7, 3, 1, 4, 8, 3, 2, 9};
std::list<int> beginners;
std::list<int> pros;

2. Grouping Players

for (std::list<int>::iterator it = allPlayers.begin(); it != allPlayers.end(); ++it) {
    int rating = *it;
    if (rating >= 1 && rating <= 5)
        beginners.push_back(rating);
    else if (rating >= 6 && rating <= 10)
        pros.push_back(rating);
}

πŸ–¨οΈ Displaying Ratings Function

Function to Display Player Ratings:

void displayRating(const std::list<int>& playerRatings) {
    for (std::list<int>::const_iterator it = playerRatings.begin(); it != playerRatings.end(); ++it) {
        std::cout << *it << std::endl;
    }
}

Notes:

  • Uses const_iterator to ensure read-only access

  • Passes list by reference (&) to avoid unnecessary copying

  • Uses const for safety β€” to prevent modification

Example Usage:

std::cout << "Beginners:" << std::endl;
displayRating(beginners);
 
std::cout << "Pros:" << std::endl;
displayRating(pros);

πŸ” Ordering Players by Rating

Problem:

We want the players in each group to be ordered by their rating in ascending order.

Solution: Custom Insert Function

void insertPlayerIntoOrderedList(int rating, std::list<int>& orderedPlayers) {
    for (auto it = orderedPlayers.begin(); it != orderedPlayers.end(); ++it) {
        if (*it > rating) {
            orderedPlayers.insert(it, rating);
            return;
        }
    }
    orderedPlayers.push_back(rating);
}

Use in Matchmaking Logic:

if (rating >= 1 && rating <= 5)
    insertPlayerIntoOrderedList(rating, beginners);
else if (rating >= 6 && rating <= 10)
    insertPlayerIntoOrderedList(rating, pros);

βœ… Summary: Advantages and Disadvantages of list

AdvantagesDisadvantages
Fast Insertion and Deletion (O(1))Slow Traversal and Searching (O(n))
Dynamic sizeMore memory per element (due to pointers)
Good for queues, editing text buffersNot cache-friendly

πŸ’‘ Analogy: Friends Holding Hands (Linked List)

Imagine:

  • A group of friends holding hands.

  • Each friend knows who is in front and who is behind.

  • If you join in the middle, you just link hands between two friends.

  • If you leave, the others just hold hands again.

This is how a list grows or shrinks dynamically.

But… If you’re trying to find Joe, you’d have to go person by person and ask for his name β€” very slow!


πŸ” Comparison with vector

Featurelistvector
Access TimeO(n) (need to traverse)O(1) (random access by index)
Insertion/RemovalFast at any position (O(1) with iterator)Slow (due to reallocation)
Memory LayoutNon-contiguous (more overhead)Contiguous (better cache performance)
Best ForFrequent insert/deleteFrequent access/search

Vector Analogy:

  • Like a classroom with fixed seats.

  • Easy to find a student by their seat number (index).

  • But hard to add/remove students β€” need a new room (reallocation).


πŸŽ“ Practical Programming Tip

  • If your app frequently adds/removes elements, use a list.

  • If your app frequently searches or accesses by index, use a vector.


πŸ“¦ Conclusion

  • STL containers like list help organize data efficiently.

  • Use the right container based on the operation requirements.

  • Understanding their underlying structure helps you make better coding decisions.

  • Combine your knowledge of data structures to build real-world applications like a matchmaking system in games.


References