The C++ Standard Template Library (STL) Algorithms provides a powerful suite of functions for working with data in containers like vector, deque, list, and array.
These algorithms cover common tasks such as sorting, searching, counting, and modifying data, making them invaluable for efficient and readable code.
Key Concepts of STL Algorithms
- Non-modifying Algorithms: Algorithms that work with containers without changing the data, such as find, count, accumulate.
- Modifying Algorithms: Algorithms that modify data in containers, such as fill, replace, copy.
- Sorting and Ordering Algorithms: Algorithms for sorting, reversing, and shuffling elements.
- Numeric Algorithms: Algorithms specifically for performing numerical operations, such as accumulate and partial_sum.
All STL algorithms operate on iterators, allowing them to work with various container types.
1. Non-modifying Algorithm: find
The find algorithm searches for a specific value in a range of elements and returns an iterator to the first occurrence or end if not found.
Example: Finding an Element in a vector
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; // Searching for 3 auto it = find(numbers.begin(), numbers.end(), 3); if (it != numbers.end()) { cout << "Found 3 at index " << distance(numbers.begin(), it) << endl; } else { cout << "3 not found" << endl; } return 0; }
Output:
Found 3 at index 2
2. Non-modifying Algorithm: count
The count algorithm counts the occurrences of a specific value within a range.
Example: Counting Occurrences in a vector
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 2, 4, 2, 5}; int count_of_twos = count(numbers.begin(), numbers.end(), 2); cout << "Count of 2: " << count_of_twos << endl; return 0; }
Output:
Count of 2: 3
3. Non-modifying Algorithm: accumulate
The accumulate algorithm, found in the <numeric> library, calculates the sum of elements in a range.
Example: Calculating the Sum of Elements in a vector
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; int sum = accumulate(numbers.begin(), numbers.end(), 0); cout << "Sum of elements: " << sum << endl; return 0; }
Output:
Sum of elements: 15
4. Modifying Algorithm: fill
The fill algorithm assigns a specified value to each element in a range.
Example: Filling a vector with a Specific Value
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers(5); fill(numbers.begin(), numbers.end(), 10); cout << "Filled vector: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output:
Filled vector: 10 10 10 10 10
5. Modifying Algorithm: replace
The replace algorithm replaces all occurrences of a specific value within a range.
Example: Replacing Elements in a vector
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 2, 4, 2, 5}; replace(numbers.begin(), numbers.end(), 2, 99); cout << "After replace: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output:
After replace: 1 99 3 99 4 99 5
6. Modifying Algorithm: copy
The copy algorithm copies elements from one range to another, requiring the destination range to be at least as large as the source.
Example: Copying Elements from One vector to Another
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> source = {1, 2, 3, 4, 5}; vector<int> destination(5); copy(source.begin(), source.end(), destination.begin()); cout << "Copied vector: "; for (int num : destination) { cout << num << " "; } cout << endl; return 0; }
Output:
Copied vector: 1 2 3 4 5
7. Sorting Algorithm: sort
The sort algorithm arranges elements in ascending order by default. A custom comparison function can be used for sorting in descending order.
Example: Sorting a vector in Ascending and Descending Order
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers = {4, 1, 5, 3, 2}; // Sorting in ascending order sort(numbers.begin(), numbers.end()); cout << "Ascending: "; for (int num : numbers) { cout << num << " "; } cout << endl; // Sorting in descending order sort(numbers.begin(), numbers.end(), greater<int>()); cout << "Descending: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output:
Ascending: 1 2 3 4 5 Descending: 5 4 3 2 1
8. Reversing Algorithm: reverse
The reverse algorithm reverses the order of elements in a range.
Example: Reversing a vector
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; reverse(numbers.begin(), numbers.end()); cout << "Reversed vector: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output:
Reversed vector: 5 4 3 2 1
9. Shuffling Algorithm: random_shuffle
The random_shuffle algorithm rearranges elements in random order (deprecated in C++17; std::shuffle is preferred in C++11 and newer).
Example: Shuffling Elements in a vector
#include <iostream> #include <vector> #include <algorithm> #include <cstdlib> #include <ctime> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; srand(time(0)); // Seed for randomness random_shuffle(numbers.begin(), numbers.end()); cout << "Shuffled vector: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output:
Shuffled vector: 4 1 5 2 3
10. Numeric Algorithm: partial_sum
The partial_sum algorithm calculates partial sums of elements, storing the cumulative total up to each position in the destination range.
Example: Calculating Partial Sums
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> numbers = {1, 2, 3, 4, 5}; vector<int> result(5); partial_sum(numbers.begin(), numbers.end(), result.begin()); cout << "Partial sums: "; for (int sum : result) { cout << sum << " "; } cout << endl; return 0; }
Output:
Partial sums: 1 3 6 10 15
Summary Table of STL Algorithms
Algorithm | Example | Description |
---|---|---|
find | find(v.begin(), v.end(), 3); | Searches for an element |
count | count(v.begin(), v.end(), 2); | Counts occurrences of a specific value |
accumulate | accumulate(v.begin(), v.end(), 0); | Calculates sum of elements |
fill | fill(v.begin(), v.end(), 10); | Fills elements with a specified value |
replace | replace(v.begin(), v.end(), 2, 99); | Replaces occurrences of a value |
copy | copy(source.begin(), source.end(), dest.begin()); | Copies elements to another range |
sort | sort(v.begin(), v.end()); | Sorts elements in ascending or custom order |
reverse | reverse(v.begin(), v.end()); | Reverses elements |
random_shuffle | random_shuffle(v.begin(), v.end()); | Shuffles elements randomly |
partial_sum | partial_sum(v.begin(), v.end(), result.begin()); | Calculates cumulative sums of elements |
Complete Example
This example combines several algorithms (sort, find, count, and reverse) to demonstrate their collective power.
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; int main() { vector<int> numbers = {4, 2, 5, 1, 3, 2, 4}; // Sorting sort(numbers.begin(), numbers.end()); cout << "Sorted vector: "; for (int num : numbers) { cout << num << " "; } cout << endl; // Counting occurrences of 2 int count_of_two = count(numbers.begin(), numbers.end(), 2); cout << "Count of 2: " << count_of_two << endl; // Finding the position of 5 auto it = find(numbers.begin(), numbers.end(), 5); if (it != numbers.end()) { cout << "5 found at position: " << distance(numbers.begin(), it) << endl; } else { cout << "5 not found" << endl; } // Reversing the sorted vector reverse(numbers.begin(), numbers.end()); cout << "Reversed sorted vector: "; for (int num : numbers) { cout << num << " "; } cout << endl; return 0; }
Sample Output:
Sorted vector: 1 2 2 3 4 4 5 Count of 2: 2 5 found at position: 6 Reversed sorted vector: 5 4 4 3 2 2 1
Key Takeaways
- STL Algorithms in C++ provide ready-made, optimized solutions for common operations.
- Algorithms like find, count, accumulate, sort, reverse, and shuffle simplify handling data in STL containers.