codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

74 / 87 topics
62Introduction to STL & Containers63std::array64Vectors65List & Forward List66Deque67Stack68Queue & Priority Queue69Map & Multimap70Set & Multiset71Unordered Map & Unordered Multimap72Unordered Set & Unordered Multiset73Iterators74Algorithms75Functors
Tutorials/C++ Programming/Algorithms
⚡C++ Programming

Algorithms

Updated 2026-05-12
35 min read

Algorithms

In this tutorial, we will explore the powerful algorithms provided by the Standard Template Library (STL) in C++. These algorithms are essential for efficient data manipulation and are built on top of iterators, which you already know from the previous topic. Understanding these algorithms will significantly enhance your ability to write clean and optimized C++ code.

Introduction

The STL provides a collection of generic functions that operate on sequences defined by iterators. These algorithms can be categorized into various groups such as sorting, searching, modifying, and numeric operations. Knowing how to use these algorithms effectively can greatly simplify your code and improve its performance.

In this tutorial, we will cover some of the most commonly used STL algorithms: sort, find, count, accumulate, transform, for_each, binary_search, min_element/max_element, copy, and reverse. Each algorithm has its own specific use case, and understanding them will help you write more efficient and readable code.

Core Content

1. Sorting with sort

The sort function is used to sort elements in a range. It uses the less-than operator by default but can also take a custom comparator function.

Example: Basic Sorting

C++
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6 std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
7
8 // Sort the vector in ascending order
9 std::sort(numbers.begin(), numbers.end());
10
11 // Print sorted vector
12 for (int num : numbers) {
13 std::cout << num << " ";
14 }
15
16 return 0;
17}
Output

2. Searching with find

The find function searches for a specific element in a range and returns an iterator to the first occurrence of that element.

Example: Basic Find

C++
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6 std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
7 int target = 5;
8
9 // Find the first occurrence of 'target' in the vector
10 auto it = std::find(numbers.begin(), numbers.end(), target);
11
12 if (it != numbers.end()) {
13 std::cout << "Element found at position: " << std::distance(numbers.begin(), it) << std::endl;
14 } else {
15 std::cout << "Element not found" << std::endl;
16 }
17
18 return 0;
19}
Output

4. Accumulating Values with accumulate

The accumulate function computes the sum of a range of elements, optionally using an initial value and a custom binary operation.

Example: Basic Accumulate

C++
1#include <iostream>
2#include <vector>
3#include <numeric> // For std::accumulate
4
5int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7
8 // Compute the sum of the vector elements
9 int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
10
11 std::cout << "Sum of elements: " << sum << std::endl;
12
13 return 0;
14}
Output

5. Transforming Elements with transform

The transform function applies a given operation to each element in a range and stores the result in another range.

Example: Basic Transform

C++
1#include <iostream>
2#include <vector>
3#include <algorithm> // For std::transform
4
5int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7 std::vector<int> result(numbers.size());
8
9 // Square each element in the vector
10 std::transform(numbers.begin(), numbers.end(), result.begin(), [](int x) { return x * x; });
11
12 // Print transformed vector
13 for (int num : result) {
14 std::cout << num << " ";
15 }
16
17 return 0;
18}
Output

7. Binary Search with binary_search

The binary_search function searches for a specific element in a sorted range and returns true if the element is found.

Example: Basic Binary Search

C++
1#include <iostream>
2#include <vector>
3#include <algorithm> // For std::sort and std::binary_search
4
5int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7 int target = 3;
8
9 // Sort the vector (required for binary search)
10 std::sort(numbers.begin(), numbers.end());
11
12 // Perform binary search
13 if (std::binary_search(numbers.begin(), numbers.end(), target)) {
14 std::cout << "Element found" << std::endl;
15 } else {
16 std::cout << "Element not found" << std::endl;
17 }
18
19 return 0;
20}
Output

9. Copying Elements with copy

The copy function copies elements from one range to another.

Example: Basic Copy

C++
1#include <iostream>
2#include <vector>
3#include <algorithm> // For std::copy
4
5int main() {
6 std::vector<int> source = {1, 2, 3, 4, 5};
7 std::vector<int> destination(source.size());
8
9 // Copy elements from source to destination
10 std::copy(source.begin(), source.end(), destination.begin());
11
12 // Print copied vector
13 for (int num : destination) {
14 std::cout << num << " ";
15 }
16
17 return 0;
18}
Output

Practical Example

Let's create a complete program that demonstrates the use of several STL algorithms. This program will sort a vector, find an element, count occurrences, compute the sum, square each element, print all elements, perform a binary search, find the minimum and maximum elements, copy the vector, and reverse it.

C++
1#include <iostream>
2#include <vector>
3#include <algorithm> // For various algorithms
4#include <numeric> // For std::accumulate
5
6void print(int x) {
7 std::cout << x << " ";
8}
9
10int main() {
11 std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
12 int target = 5;
13
14 // Sort the vector
15 std::sort(numbers.begin(), numbers.end());
16 std::cout << "Sorted vector: ";
17 for (int num : numbers) {
18 std::cout << num << " ";
19 }
20 std::cout << std::endl;
21
22 // Find the first occurrence of 'target'
23 auto it = std::find(numbers.begin(), numbers.end(), target);
24 if (it != numbers.end()) {
25 std::cout << "Element found at position: " << std::distance(numbers.begin(), it) << std::endl;
26 } else {
27 std::cout << "Element not found" << std::endl;
28 }
29
30 // Count the occurrences of 'target'
31 int count = std::count(numbers.begin(), numbers.end(), target);
32 std::cout << "Element " << target << " occurs " << count << " times." << std::endl;
33
34 // Compute the sum of the vector elements
35 int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
36 std::cout << "Sum of elements: " << sum << std::endl;
37
38 // Square each element in the vector
39 std::vector<int> result(numbers.size());
40 std::transform(numbers.begin(), numbers.end(), result.begin(), [](int x) { return x * x; });
41 std::cout << "Squared elements: ";
42 for (int num : result) {
43 std::cout << num << " ";
44 }
45 std::cout << std::endl;
46
47 // Print each element in the vector
48 std::cout << "Original vector: ";
49 std::for_each(numbers.begin(), numbers.end(), print);
50 std::cout << std::endl;
51
52 // Perform binary search (vector must be sorted)
53 if (std::binary_search(numbers.begin(), numbers.end(), target)) {
54 std::cout << "Element found in binary search" << std::endl;
55 } else {
56 std::cout << "Element not found in binary search" << std::endl;
57 }
58
59 // Find the minimum and maximum elements
60 auto min_it = std::min_element(numbers.begin(), numbers.end());
61 auto max_it = std::max_element(numbers.begin(), numbers.end());
62 std::cout << "Minimum element: " << *min_it << std::endl;
63 std::cout << "Maximum element: " << *max_it << std::endl;
64
65 // Copy the vector
66 std::vector<int> copied(numbers.size());
67 std::copy(numbers.begin(), numbers.end(), copied.begin());
68 std::cout << "Copied vector: ";
69 for (int num : copied) {
70 std::cout << num << " ";
71 }
72 std::cout << std::endl;
73
74 // Reverse the vector
75 std::reverse(copied.begin(), copied.end());
76 std::cout << "Reversed vector: ";
77 for (int num : copied) {
78 std::cout << num << " ";
79 }
80 std::cout << std::endl;
81
82 return 0;
83}
Output
Sorted vector: 1 2 5 5 6 9 
Element found at position: 2
Element 5 occurs 2 times.
Sum of elements: 28
Squared elements: 1 4 25 25 36 81 
Original vector: 1 2 5 5 6 9 
Element found in binary search
Minimum element: 1
Maximum element: 9
Copied vector: 1 2 5 5 6 9 
Reversed vector: 9 6 5 5 2 1

Summary

In this tutorial, we covered several important STL algorithms:

  • sort: Sorts elements in a range.
  • find: Searches for an element in a range.
  • count: Counts occurrences of an element in a range.
  • accumulate: Computes the sum or product of elements in a range.
  • transform: Applies a function to each element in a range.
  • for_each: Iterates over each element in a range and applies a function.
  • binary_search: Searches for an element in a sorted range.
  • min_element/max_element: Finds the smallest/largest element in a range.
  • copy: Copies elements from one range to another.
  • reverse: Reverses the order of elements in a range.

Understanding these algorithms and how to use them effectively will greatly enhance your ability to write efficient and clean C++ code.

What's Next?

In the next tutorial, we will explore functors (function objects) in C++. Functors are objects that can be called like functions and are often used with STL algorithms to provide more flexible behavior. This will further expand your toolkit for writing powerful and reusable C++ programs.

Stay tuned!


PreviousIteratorsNext Functors

Recommended Gear

IteratorsFunctors