-
Hajipur, Bihar, 844101
In C++, algorithms are predefined functions in the Standard Template Library (STL) that make it easy to perform operations on data structures like vectors, lists, sets, and maps. These algorithms are efficient, reusable, and designed to handle common tasks such as sorting, searching, counting, and manipulating elements.
The header file <algorithm> includes most of these functions, allowing you to focus more on logic than implementation details.
Using STL algorithms helps in writing cleaner and faster programs. Here are some benefits:
Optimized Performance: Algorithms are pre-tested and written by experts for efficiency.
Simplicity: You can perform complex tasks with a single line of code.
Flexibility: They work with different data structures using iterators.
Reusability: The same algorithm can be applied to multiple containers.
Example:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {4, 1, 7, 3, 9};
sort(numbers.begin(), numbers.end());
for (int n : numbers)
cout << n << " ";
return 0;
}
Output:
1 3 4 7 9
STL algorithms can be grouped into categories based on what they do. Let’s go through the most commonly used ones.
The sort() function arranges elements in ascending order by default.
sort(numbers.begin(), numbers.end());
To sort in descending order:
sort(numbers.begin(), numbers.end(), greater<int>());
Other sorting-related functions include:
stable_sort() – Maintains the order of equal elements.
partial_sort() – Sorts only a specific portion of the data.
Searching algorithms help find specific elements within a container.
find() – Locates the first occurrence of a value.
auto it = find(numbers.begin(), numbers.end(), 7);
if (it != numbers.end())
cout << "Found at position: " << distance(numbers.begin(), it);
else
cout << "Not found";
binary_search() – Works only on sorted data to quickly check if an element exists.
bool exists = binary_search(numbers.begin(), numbers.end(), 4);
Counting functions let you know how many times an element appears.
count() – Counts occurrences of a specific element.
int c = count(numbers.begin(), numbers.end(), 3);
cout << "Count of 3: " << c;
count_if() – Counts elements based on a condition.
int evenCount = count_if(numbers.begin(), numbers.end(), [](int x) { return x % 2 == 0; });
STL provides functions to quickly find the smallest and largest values.
cout << "Min: " << *min_element(numbers.begin(), numbers.end());
cout << " Max: " << *max_element(numbers.begin(), numbers.end());
To calculate the sum or total of elements, use the accumulate() function from the <numeric> header.
#include <numeric>
int total = accumulate(numbers.begin(), numbers.end(), 0);
cout << "Total: " << total;
The remove() algorithm deletes all occurrences of a specific value.
numbers.erase(remove(numbers.begin(), numbers.end(), 3), numbers.end());
The replace() algorithm substitutes one value with another.
replace(numbers.begin(), numbers.end(), 4, 10);
The copy() function transfers elements from one container to another.
vector<int> copyVec(5);
copy(numbers.begin(), numbers.end(), copyVec.begin());
There’s also copy_if(), which copies elements based on a condition.
copy_if(numbers.begin(), numbers.end(), copyVec.begin(), [](int x) { return x > 5; });
The merge() function combines two sorted containers into one.
vector<int> a = {1, 3, 5};
vector<int> b = {2, 4, 6};
vector<int> merged(6);
merge(a.begin(), a.end(), b.begin(), b.end(), merged.begin());
For mathematical set operations:
set_union()
set_intersection()
set_difference()
These work on sorted containers and help find relationships between data sets.
The transform() function applies a custom operation to each element.
transform(numbers.begin(), numbers.end(), numbers.begin(), [](int x) { return x * 2; });
It’s useful for modifying values in bulk or applying mathematical logic to elements.
To reverse the order of elements:
reverse(numbers.begin(), numbers.end());
To rotate elements (move first elements to the end):
rotate(numbers.begin(), numbers.begin() + 2, numbers.end());
Efficiency: The algorithms are fine-tuned for speed and reliability.
Consistency: They follow a uniform syntax and can be used across containers.
Less Code: You write less and achieve more functionality.
Error Reduction: Pre-tested functions minimize bugs and logic errors.
Scalability: Algorithms handle both small and large data efficiently.
C++ STL algorithms are essential for performing operations like sorting, searching, counting, and modifying data without writing lengthy code. They are efficient, easy to use, and work with various STL containers through iterators. Understanding how to apply these algorithms allows developers to build cleaner, faster, and more maintainable programs.
Write a C++ program to sort a vector of integers in ascending and descending order using STL algorithms.
Create a program that searches for a specific element in a vector using the find() function.
Write a program to count the number of even numbers in an array using count_if().
Develop a program to find both the smallest and largest numbers in a vector using min_element() and max_element().
Build a program to calculate the total sum of all elements in a vector using accumulate().
Write a program that removes all occurrences of a given number from a vector using remove().
Create a program to merge two sorted arrays into one sorted array using merge().
Write a program to double each element in a vector using the transform() function.
Build a program that reverses the elements of a vector using reverse().
Write a program that replaces all negative numbers in a vector with zero using replace_if().