Lambda expressions are a powerful feature in C++ that allow you to define anonymous functions directly in your code.
They can be effectively used as projection functions due to their concise syntax and ability to capture variables from their enclosing scope.
Consider sorting a collection of Player
objects by their Level
attribute using a lambda expression as the projection function:
#include <vector>
#include <iostream>
#include <algorithm>
struct Player {
std::string Name;
int Level;
};
int main() {
std::vector<Player> Party {
{"Legolas", 49},
{"Gimli", 47},
{"Gandalf", 53}
};
std::ranges::sort(Party, {},
[](const Player& P) { return P.Level; });
for (const auto& P : Party) {
std::cout << "[" << P.Level << "] "
<< P.Name << "\n";
}
}
[47] Gimli
[49] Legolas
[53] Gandalf
In this example, the lambda expression [](const Player& P) { return P.Level; }
is used as the projection function to extract the Level
attribute from each Player
object.
Lambdas can also capture variables from their enclosing scope. This is useful when the projection needs additional context:
#include <vector>
#include <iostream>
#include <algorithm>
struct Player {
std::string Name;
int Level;
};
int main() {
std::vector<Player> Party {
{"Legolas", 49},
{"Gimli", 47},
{"Gandalf", 53}
};
int levelCap = 50;
std::ranges::sort(Party, {},
[levelCap](const Player& P) {
return (P.Level < levelCap)
? P.Level
: levelCap;
}
);
for (const auto& P : Party) {
std::cout << "[" << P.Level << "] "
<< P.Name << "\n";
}
}
[47] Gimli
[49] Legolas
[50] Gandalf
In this example, the lambda captures the levelCap
variable and uses it within the projection function.
Using lambda expressions as projection functions enhances the flexibility and readability of your code, allowing you to define custom projections directly where they are needed.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to use projection functions to apply range-based algorithms on derived data