🧮
STL

STL Algorithms

sort, find, count — <algorithm>
💡 <algorithm> header ek ready-made toolbox hai — sort karna, dhundna, count karna jaisi bahut common cheezein khud loop likhne ke bajaye, ek function call se ho jaati hain, jo already tested aur optimized hai.

<algorithm> header dozens of ready-made functions deta hai jo kisi bhi container par kaam karte hain (iterators ke through) — sort() se sorting, find() se searching, count() se counting, reverse() se reverse karna, waghera. Khud loop likhne se ye zyada readable, aur usually zyada optimized bhi hote hain.

#include <algorithm>
#include <vector>
using namespace std;

int main() {
  vector<int> nums = {5, 2, 8, 1, 9};

  sort(nums.begin(), nums.end());   // ascending sort
  for (int n : nums) cout << n << " ";  // 1 2 5 8 9
  cout << endl;

  auto it = find(nums.begin(), nums.end(), 8);
  if (it != nums.end()) cout << "8 mila!" << endl;

  int c = count(nums.begin(), nums.end(), 5);
  cout << c << endl;   // 1

  reverse(nums.begin(), nums.end());
  for (int n : nums) cout << n << " "; // 9 8 5 2 1
  return 0;
}
🧮
<algorithm> header ek ready-made toolbox hai — sort karna, dhundna, count karna jaisi bahut common cheezein khud loop likhne ke bajaye, ek function call se ho jaati hain, jo already tested aur optimized hai.
1 / 2
⚡ झट से Recap
  • sort(), find(), count(), reverse() — bahut common STL algorithms
  • Sab begin()/end() iterators leke kaam karte hain, kisi bhi container par
  • Khud loop likhne se zyada readable aur optimized
इस page में (2 subtopics)

Bahut saare STL algorithms ek "predicate" (custom logic function) le sakte hain — lambda expressions (aage detail mein seekhenge) se inline custom conditions likhna bahut common hai, jaise sort() ko custom comparison dena, ya count_if() se conditional counting.

#include <algorithm>
vector<int> nums = {5, 2, 8, 1, 9};

sort(nums.begin(), nums.end(), [](int a, int b) {
  return a > b;   // descending order — custom lambda comparison
});

int evenCount = count_if(nums.begin(), nums.end(), [](int n) {
  return n % 2 == 0;
});
cout << evenCount << endl;
💡Tip: greater<int>() built-in comparator ka use karna sort(nums.begin(), nums.end(), greater<int>()); ke through bhi possible hai — same result, lambda ki zaroorat nahi simple descending sort ke liye.

accumulate() (header <numeric>) ek range ke sab elements ko combine karta hai — default sum, lekin custom operation bhi de sakte ho (jaise product, ya string concatenation).

#include <numeric>
vector<int> nums = {1, 2, 3, 4, 5};

int sum = accumulate(nums.begin(), nums.end(), 0);  // 15 (0 = starting value)
cout << sum << endl;

int product = accumulate(nums.begin(), nums.end(), 1, [](int a, int b) {
  return a * b;
});
cout << product << endl;  // 120
💡Tip: accumulate() ka teesra argument "initial value" hai — sum ke liye 0 se shuru karo, product ke liye 1 se (warna sab kuch 0 ho jaayega multiply karte hi).