← SEARCHABLE ARCHIVE
C / C++ · 2026-07-07

C++ from Basics to Mastery — Part 11

Using Lambda and Standard Algorithms

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

Code to find or sort specific monsters in a container and remove dead monsters appears frequently. You can create your own with a for statement, but using a standard algorithm makes the purpose of the code more visible.

Lambda

A lambda is a function that you write directly without a name.

int monsterId = 10;

auto isTarget = [monsterId](const std::shared_ptr<Monster>& monster)
{
    return monster->GetId() == monsterId;
};

[]is the capture list. [monsterId]captures the value by copying it,[&]captures external variables by reference.[this]uses the current object.

Reference capture is convenient, but can be dangerous if the lambda survives longer than the original variable. The code is easier to read if you clearly capture only the necessary values.

find_if

auto iter = std::find_if(
    activeMonsters.begin(),
    activeMonsters.end(),
    [monsterId](const auto& monster)
    {
        return monster->GetId() == monsterId;
    }
);

if (iter != activeMonsters.end())
{
    currentTarget = *iter;
}

find_if returns an iterator of the first element that satisfies the condition. If not found, the end of the passed range is returned.

sort

Sort monsters with the lowest health first, and if the health is the same, you can place the monsters with the lower ID first.

std::sort(
    activeMonsters.begin(),
    activeMonsters.end(),
    [](const auto& a, const auto& b)
    {
        if (a->GetHealth() != b->GetHealth())
        {
            return a->GetHealth() < b->GetHealth();
        }

        return a->GetId() < b->GetId();
    }
);

If the comparison function returns true, it means that a must come before b. If the comparison criteria are contradictory, the sorting results cannot be trusted, so strict abbreviated order must be observed.

remove_if and erase

auto newEnd = std::remove_if(
    activeMonsters.begin(),
    activeMonsters.end(),
    [](const auto& monster)
    {
        return monster->IsDead();
    }
);

activeMonsters.erase(newEnd, activeMonsters.end());

remove_if does not directly reduce the container size. Moves the remaining elements forward and returns the new logical end. The actual erasure is performed by erase.

When an element is deleted from a vector, subsequent iterators and references may become invalid. When a shared_ptr element is removed, its reference count is decremented, and if it was the last owner, the object is also destroyed.

Using lambda and algorithms does not necessarily make the code faster. Instead, the biggest advantage is that the intention of finding, sorting, and removing is clearly expressed in the code.