Home > Article > Backend Development > Improvements to STL function objects in C++ 11 and C++ 14?
STL function objects have undergone major improvements, including perfect forwarding and move semantics in C 11, and function pointer encapsulation and generic lambdas in C 14. These improvements enhance usability, efficiency, and flexibility; for example, a generic lambda simplifies the writing of sorting function objects by simply using std::less{} to sort descendingly.
Improvements in STL function objects in C 11 and C 14
During the development of the C Standard Library (STL), Function objects have been significantly improved. These improvements are designed to enhance usability, efficiency and flexibility.
Improvements in C 11
Code example:
struct Forwarder { template <typename ...Args> void operator()(Args&&... args) const { std::forward<Args>(args)...; // 完美转发参数 } };
Code Example:
struct Mover { std::string value; Mover(Mover&& other) noexcept : value(std::move(other.value)) { other.value.clear(); // 移出旧值 } };
Improvements in C 14
Code example:
auto plus = std::function<int(int, int)>([](int a, int b) { return a + b; });
Code example:
auto sort_by = [](const auto& a, const auto& b) { return a < b; };
Practical case
Assume there is a data structure of student grades, now we To sort grades using STL function objects.
C 11 Code:
std::vector<int> grades = {90, 85, 95, 88, 92}; std::sort(grades.begin(), grades.end(), [](int a, int b) { return a > b; }); // 降序排序
C 14 Code:
std::vector<int> grades = {90, 85, 95, 88, 92}; std::ranges::sort(grades, std::less{}); // 降序排序
As you can see, C 14 The introduction of a generic lambda simplifies the writing of sorting function objects.
The above is the detailed content of Improvements to STL function objects in C++ 11 and C++ 14?. For more information, please follow other related articles on the PHP Chinese website!