C++ Day 38
STL Algorithms (Practical & Real-World Usage)
Until now, you have learned about loops, arrays, vectors, functions, and STL containers.
From today, you move into the real power of C++, where you stop writing long loops again and again and instead use ready-made logic provided by the Standard Template Library (STL).
These are called STL Algorithms.
1. What are STL Algorithms?
STL algorithms are predefined functions that perform common operations like:
-
searching
-
sorting
-
counting
-
modifying data
-
checking conditions
They work on ranges, not directly on containers.
A range is defined using:
This design makes algorithms container-independent.
2. Why Use STL Algorithms Instead of Loops?
Consider this loop:
Now compare with:
Advantages:
-
Less code
-
Fewer bugs
-
Easy to read
-
Optimized by compiler
-
Used in real projects and interviews
3. Required Header Files
Most algorithms:
For numeric operations:
4. sort() Algorithm
Sorting in Ascending Order
Output:
Sorting in Descending Order
Sorting Using Lambda Function
Lambda allows custom logic.
This is commonly used in competitive programming.
5. find() Algorithm
Used to search an element.
find() returns an iterator, not index.
6. count() Algorithm
Counts how many times a value appears.
If 2 appears 3 times, cnt = 3.
7. count_if() Algorithm
Used when condition is needed.
Example: Count even numbers.
This replaces a long loop with if condition.
8. find_if() Algorithm
Finds first element that satisfies a condition.
Useful when exact value is not known.
9. accumulate() Algorithm
Used to calculate:
-
sum
-
product
-
custom accumulation
Sum of Elements
Product of Elements
10. max_element() and min_element()
Returns iterator, so * is required.
11. reverse() Algorithm
No need to write swapping logic manually.
12. for_each() Algorithm
Used to apply an operation to every element.
Common in functional-style coding.
13. all_of(), any_of(), none_of()
Check if all elements are positive
Check if any element is negative
14. Real-World Thinking
STL algorithms help you:
-
write cleaner production code
-
perform faster coding in contests
-
clear interviews easily
-
avoid logical mistakes
In professional C++ code, manual loops are avoided unless necessary.
15. Common Mistakes to Avoid
-
Forgetting
#include <algorithm> -
Forgetting iterators work on ranges
-
Forgetting algorithms return iterators
-
Writing loops when algorithms already exist
16. Summary (Day 38)
Today you learned:
-
What STL algorithms are
-
Why they are important
-
How to use sort, find, count, accumulate
-
How lambda functions simplify logic
-
How to write clean, professional C++ code
Comments
Post a Comment