Skip to main content

C++ Day 39

  C++ Day 39 STL Containers (Deep Understanding & Real Usage) Till now, you already know arrays, vectors, loops, and STL algorithms. Today, we go one step deeper and understand STL containers , which are the backbone of modern C++ programming. In real projects and competitive coding, choice of container matters a lot. 1. What are STL Containers? STL containers are data structures provided by C++ to store data efficiently. They handle: memory management resizing element access performance optimization You focus on logic , not memory handling. 2. Categories of STL Containers STL containers are mainly divided into: Sequence Containers Associative Containers Unordered Containers Container Adapters 3. Sequence Containers These store data in sequence . 3.1 Vector Most used container in C++. vector< int > v; Key Features: Dynamic size Contiguous memory Fast random access Slower insertion in middle Example: v. push_...

C++ Day 38

 

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:

container.begin(), container.end()

This design makes algorithms container-independent.


2. Why Use STL Algorithms Instead of Loops?

Consider this loop:

int sum = 0; for(int i = 0; i < v.size(); i++) { sum += v[i]; }

Now compare with:

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

Advantages:

  • Less code

  • Fewer bugs

  • Easy to read

  • Optimized by compiler

  • Used in real projects and interviews


3. Required Header Files

Most algorithms:

#include <algorithm>

For numeric operations:

#include <numeric>

4. sort() Algorithm

Sorting in Ascending Order

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

Output:

1 2 4 7 9

Sorting in Descending Order

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

Sorting Using Lambda Function

Lambda allows custom logic.

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

This is commonly used in competitive programming.


5. find() Algorithm

Used to search an element.

auto it = find(v.begin(), v.end(), 7); if(it != v.end()) cout << "Element Found"; else cout << "Not Found";

find() returns an iterator, not index.


6. count() Algorithm

Counts how many times a value appears.

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

If 2 appears 3 times, cnt = 3.


7. count_if() Algorithm

Used when condition is needed.

Example: Count even numbers.

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

This replaces a long loop with if condition.


8. find_if() Algorithm

Finds first element that satisfies a condition.

auto it = find_if(v.begin(), v.end(), [](int x) { return x > 5; });

Useful when exact value is not known.


9. accumulate() Algorithm

Used to calculate:

  • sum

  • product

  • custom accumulation

Sum of Elements

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

Product of Elements

int product = accumulate(v.begin(), v.end(), 1, multiplies<int>());

10. max_element() and min_element()

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

Returns iterator, so * is required.


11. reverse() Algorithm

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

No need to write swapping logic manually.


12. for_each() Algorithm

Used to apply an operation to every element.

for_each(v.begin(), v.end(), [](int x) { cout << x << " "; });

Common in functional-style coding.


13. all_of(), any_of(), none_of()

Check if all elements are positive

bool result = all_of(v.begin(), v.end(), [](int x) { return x > 0; });

Check if any element is negative

bool result = any_of(v.begin(), v.end(), [](int x) { return x < 0; });

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

Popular posts from this blog

C++ Day 35

  C++ Day 34: Layout Layouts (Part 2) We’ll cover: Constructer Layout Adjuster Layout Decorator Layout practise Task 🔹 1. developer form (creational) used to make compound objects measure away step ✅ employ case: you need to form associate in nursing aim (like amp pizza pie calculator house) with elective parameters example: cpp copy edit class calculator {     train Methodor gpu ram; public:     family developer {         train Methodor gpu ram;     public:         developer setcpu(string c) { Methodor = c; take *this; }         developer setgpu(string g) { gpu = g; take *this; }         developer setram(string r) { run = r; take *this; }         calculator Construct() {             take Calculater(cpu gpu ram);         }     };     Calculater(string snow train m train r) : cpu(c) gp...

C++ Day 33

  C++ Day 33: Smart Pointers & Memory Management 🔹 1. wherefore forward pointers in c++ hand-operated green / cancel is error-prone: memory leaks 🧠 double deletes ❌ dangling pointers 💥 smart pointers care store mechanically exploitation raii (Supply skill is initialization) 🔹 ii. Types of Smart Pointers in C++ ✅ std::unique_ptr Sole ownership of a Supply. Cannot be copied. Automatically deletes the Supply when it goes out of scope. cpp Copy Edit #include  unique_ptr ptr1 = make_unique(10); cout << *ptr1 << endl; // 10 You can transfer ownership: cpp Copy Edit unique_ptr ptr2 = move(ptr1); ✅ std::shared_ptr Shared ownership multiple shared_ptrs can point to the same object. Uses reference counting to track how many owners. cpp Copy Edit shared_ptr p1 = make_shared(100); shared_ptr p2 = p1;  // Reference count = 2 When count goes to 0 memory is released. ✅ std::weak_ptr Non-owning reference to a shared_ptr-managed object. Used to break cyclic references ...

CSES Increasing Subsequence solution

 You are given an array containing  n n n integers. Your task is to determine the longest increasing subsequence in the array, i.e., the longest subsequence where every element is larger than the previous one. A subsequence is a sequence that can be derived from the array by deleting some elements without changing the order of the remaining elements. Input The first line contains an integer n n n : the size of the array. After this there are n n n integers x 1 , x 2 , … , x n x_1,x_2,\ldots,x_n x 1 ​ , x 2 ​ , … , x n ​ : the contents of the array. Output Print the length of the longest increasing subsequence. Constraints 1 ≤ n ≤ 2 ⋅ 1 0 5 1 \le n \le 2 \cdot 10^5 1 ≤ n ≤ 2 ⋅ 1 0 5 1 ≤ x i ≤ 1 0 9 1 \le x_i \le 10^9 1 ≤ x i ​ ≤ 1 0 9 Example Input: 8 7 3 5 3 6 2 9 8 Output: 4 #include < bits / stdc ++. h > using namespace std ; void solve (){ int n ; cin >> n ; vector <int> arr ( n ); for ( int i = 0 ; i < n ; i ++)...