C++ Algorithms
Powerful built-in functions for data manipulation
🔧 What are C++ Algorithms?
C++ algorithms are pre-built functions in the <algorithm> header that perform common operations on containers like sorting, searching, and transforming data efficiently and safely.
#include <algorithm>
#include <vector>
std::vector<int> nums = {3, 1, 4, 1, 5};
std::sort(nums.begin(), nums.end());
// nums is now {1, 1, 3, 4, 5}
Essential Algorithm Categories
Sorting
Arrange elements in order
std::sort(vec.begin(), vec.end());
Searching
Find elements in containers
std::find(vec.begin(), vec.end(), 42);
Accumulating
Combine elements into single value
std::accumulate(vec.begin(), vec.end(), 0);
Transforming
Modify elements with functions
std::transform(vec.begin(), vec.end(),
vec.begin(), [](int x){ return x*2; });
🔹 Sorting Algorithms
Sorting is a fundamental operation that organizes data in a specific order, dramatically improving search
efficiency and data readability. In C++, the Standard Template Library (STL) provides the powerful
std::sort() algorithm in the <algorithm> header. It can sort containers like vectors
and arrays in ascending order by default, and descending order using the std::greater<>()
comparator. Efficient sorting (often O(N log N)) is the backbone of functionalities like displaying leaderboards,
organizing inventory, preparing data for binary search, and rendering graphically ordered elements.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {64, 34, 25, 12, 22, 11, 90};
// Sort in ascending order
std::sort(numbers.begin(), numbers.end());
// Sort in descending order
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
// Custom sorting with lambda
std::sort(numbers.begin(), numbers.end(),
[](int a, int b) { return a > b; });
return 0;
}
Result:
Original: {64, 34, 25, 12, 22, 11, 90}
Ascending: {11, 12, 22, 25, 34, 64, 90}
Descending: {90, 64, 34, 25, 22, 12, 11}
🔹 Finding Elements
Locating specific elements within a data collection is performed using search algorithms like linear search
or the more efficient binary search on sorted data. The STL provides std::find() for
linear searches and std::binary_search() or std::lower_bound() for sorted ranges. The
std::count() algorithm tallies occurrences of a value. These operations are indispensable for features
like checking if a username already exists in a database, filtering items that meet a criterion, analyzing frequency
of data points, or implementing autocomplete functionality in search boxes.
#include <algorithm>
#include <vector>
int main() {
std::vector<int> data = {1, 3, 5, 7, 9, 11};
// Find specific value
auto it = std::find(data.begin(), data.end(), 7);
if (it != data.end()) {
std::cout << "Found 7 at position: " << (it - data.begin());
}
// Find first even number
auto even = std::find_if(data.begin(), data.end(),
[](int x) { return x % 2 == 0; });
// Count occurrences
int count = std::count(data.begin(), data.end(), 5);
return 0;
}
Result:
Found 7 at position: 3
Count of 5: 1
🔹 Accumulate Operations
Accumulate operations combine elements in a sequence using mathematical or custom functions. The
std::accumulate algorithm from the <numeric> header can sum elements, multiply them,
or apply more complex reductions. It takes a range and an initial value, then successively applies an operation. For
instance, summing a vector of integers or calculating the product of a list of floats is efficient with accumulate,
making it essential for data aggregation in C++.
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Sum all elements
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
// Product of all elements
int product = std::accumulate(numbers.begin(), numbers.end(), 1,
std::multiplies<int>());
// Custom accumulation with lambda
int sum_of_squares = std::accumulate(numbers.begin(), numbers.end(), 0,
[](int acc, int x) {
return acc + x * x;
});
return 0;
}
Result:
Sum: 15 (1+2+3+4+5)
Product: 120 (1×2×3×4×5)
Sum of squares: 55 (1+4+9+16+25)
🔹 Transform Operations
Transformation applies a function to each element, mapping a range to a new set of values. The
std::transform algorithm is commonly used for operations like squaring numbers, doubling values, or
converting types (e.g., numbers to strings). This creates a new sequence where each output corresponds to an input
element, allowing for data normalization, format conversion, or feature computation in pipelines.
#include <algorithm>
#include <vector>
int main() {
std::vector<int> input = {1, 2, 3, 4, 5};
std::vector<int> output(input.size());
// Double each element
std::transform(input.begin(), input.end(), output.begin(),
[](int x) { return x * 2; });
// Transform in-place (square each element)
std::transform(input.begin(), input.end(), input.begin(),
[](int x) { return x * x; });
// Transform two ranges
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6};
std::vector<int> result(3);
std::transform(a.begin(), a.end(), b.begin(), result.begin(),
std::plus<int>());
return 0;
}
Result:
Doubled: {2, 4, 6, 8, 10}
Squared: {1, 4, 9, 16, 25}
Sum of ranges: {5, 7, 9}