🧠 C++ Algorithm – Built-in Power Tools for Smart Coding
The C++ <algorithm>
header gives you powerful built-in tools to sort, search, reverse, and more—so you can focus on the logic, not the low-level loops.
Think of it like a toolbox 🧰 where the hard work is already done for you!
📚 What’s Inside <algorithm>?
Here are some of the most useful functions from <algorithm>
:
sort()
– Sort elementsreverse()
– Reverse a rangemin()
,max()
– Get min or max of two valuescount()
– Count how many times a value appearsfind()
– Find a valueaccumulate()
– Add up values (from<numeric>
)
🔧 Example: Sorting and Reversing
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> nums = {30, 10, 20, 50, 40}; sort(nums.begin(), nums.end()); cout << "Sorted: "; for (int n : nums) cout << n << " "; reverse(nums.begin(), nums.end()); cout << "\nReversed: "; for (int n : nums) cout << n << " "; return 0; }
🔍 Example: Find, Count and Max
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> nums = {10, 20, 30, 20, 10, 20}; cout << "Count of 20: " << count(nums.begin(), nums.end(), 20) << endl; auto it = find(nums.begin(), nums.end(), 30); if (it != nums.end()) { cout << "Found 30 at position: " << (it - nums.begin()) << endl; } int a = 5, b = 10; cout << "Max: " << max(a, b) << ", Min: " << min(a, b) << endl; return 0; }
✅ Summary
<algorithm>
makes coding faster and easier- Use functions like
sort()
,reverse()
,find()
to save time - Simple, clean, and powerful tools for everyday tasks