C++ Algorithm

⚙️ C++ Algorithms (STL)

The C++ Standard Template Library (STL) provides a powerful set of algorithms in the <algorithm> header.
These algorithms work on ranges of elements defined by iterators, not on containers directly.


 1. Why Use STL Algorithms?

  • Ready-made, optimized solutions

  • Cleaner and shorter code

  • Work with all STL containers

  • Reduce bugs and improve performance


 2. Include Header

#include <algorithm>

 3. Sorting Algorithms

sort() (Most Used)

vector<int> v = {4, 1, 3, 2};
sort(v.begin(), v.end());

Descending order:

sort(v.begin(), v.end(), greater<int>());

stable_sort()

Preserves relative order of equal elements.

stable_sort(v.begin(), v.end());

4. Searching Algorithms

find()

auto it = find(v.begin(), v.end(), 3);
if (it != v.end())
cout << "Found";

binary_search() (Sorted Required)

bool found = binary_search(v.begin(), v.end(), 3);

lower_bound() and upper_bound()

auto lb = lower_bound(v.begin(), v.end(), 3); // ≥ 3
auto ub = upper_bound(v.begin(), v.end(), 3); // > 3

 5. Counting Algorithms

int c = count(v.begin(), v.end(), 2);

Conditional count:

int c = count_if(v.begin(), v.end(),
[](int x){ return x % 2 == 0; });

 6. Min / Max Algorithms

int mn = *min_element(v.begin(), v.end());
int mx = *max_element(v.begin(), v.end());

 7. Modify Sequence Algorithms

reverse()

reverse(v.begin(), v.end());

replace()

replace(v.begin(), v.end(), 2, 10);

remove() + erase() (Important!)

v.erase(remove(v.begin(), v.end(), 3), v.end());

 8. Accumulate & Numeric Algorithms

#include <numeric>

int sum = accumulate(v.begin(), v.end(), 0);


 9. Partitioning Algorithms

partition(v.begin(), v.end(),
[](int x){ return x % 2 == 0; });

 10. Heap Algorithms

make_heap(v.begin(), v.end());
pop_heap(v.begin(), v.end());

 11. Set Algorithms (Sorted Required)

vector<int> a = {1, 2, 3};
vector<int> b = {3, 4};
vector<int> result;
set_union(a.begin(), a.end(),
b.begin(), b.end(),
back_inserter(result));


 12. Algorithms with Lambdas

sort(v.begin(), v.end(),
[](int a, int b) { return a > b; });

 13. Common Algorithm Complexity

AlgorithmComplexity
sortO(n log n)
findO(n)
binary_searchO(log n)
countO(n)

❌ Common Mistakes

sort(list.begin(), list.end()); // ❌ list has no random access

✔ Use:

list.sort();

📌 Summary

  • STL algorithms operate on iterator ranges

  • Independent of container type

  • Highly optimized and reusable

  • Combine with lambdas for expressive code

  • Core skill for C++ interviews and projects

You may also like...