Loading lessons...
STL Algorithms and Function Objects
STL Algorithms and Function Objects
The STL algorithms are about 60 ready-made function templates (mostly in <algorithm>, a few in <numeric>) for searching, sorting, counting, copying, transforming and more. They work on ranges of iterators [first, last), not on containers, so one sort or find serves vectors, deques, arrays and any container with suitable iterators. Many algorithms accept a function object (or a function pointer) that customises what they do: how to compare, which elements to pick, what to apply.
1. How Algorithms Are Called
sort(v.begin(), v.end()); // whole vector
sort(v.begin(), v.begin() + 3); // only the first 3 elements
sort(arr, arr + n); // ordinary array: pointers are iterators
it = find(v.begin(), v.end(), 42); // returns v.end() if not found- Algorithms never change the size of a container: they can rearrange or overwrite elements, but they cannot insert or erase (they have only iterators, not the container).
- An algorithm that needs a certain iterator category works only with containers that provide it:
sortneeds random-access iterators (vector, deque, array) and so does not work withlist.
2. Categories of Algorithms
| Category | Examples | What they do |
|---|---|---|
| Non-mutating (non-modifying) | find, find_if, count, count_if, for_each, search, equal, min_element, max_element | read elements without changing them |
| Mutating (modifying) | copy, fill, transform, replace, remove, reverse, rotate, swap, unique | change element values or their order |
| Sorting and searching | sort, stable_sort, partial_sort, binary_search, lower_bound, upper_bound, merge | order a range or search a sorted range |
| Set algorithms | set_union, set_intersection, set_difference, includes | set operations on sorted ranges |
| Heap algorithms | make_heap, push_heap, pop_heap, sort_heap | maintain a range as a heap |
| Min/max | min, max, min_element, max_element | smallest and largest |
Numeric (<numeric>) | accumulate, inner_product, partial_sum, adjacent_difference | arithmetic over ranges |
3. Non-Mutating Algorithms
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isEven(int x) {
return x % 2 == 0;
} // a predicate: returns bool
void printItem(int x) {
cout << x << " ";
}
int main() {
int a[] = {7, 2, 9, 4, 2, 8, 5};
vector<int> v(a, a + 7);
cout << "elements: ";
for_each(v.begin(), v.end(), printItem); // apply a function to each element
cout << endl;
vector<int>::iterator it = find(v.begin(), v.end(), 9);
if (it != v.end()) {
cout << "9 found at position " << (it - v.begin()) << endl;
}
cout << "count of 2: " << count(v.begin(), v.end(), 2) << endl;
cout << "even numbers: " << count_if(v.begin(), v.end(), isEven) << endl;
it = find_if(v.begin(), v.end(), isEven);
cout << "first even number: " << *it << endl;
cout << "min: " << *min_element(v.begin(), v.end())
<< ", max: " << *max_element(v.begin(), v.end()) << endl;
return 0;
}Output:
elements: 7 2 9 4 2 8 5
9 found at position 2
count of 2: 2
even numbers: 4
first even number: 2
min: 2, max: 94. Mutating Algorithms
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int square(int x) {
return x * x;
}
void show(const char* label, const vector<int>& v) {
cout << label;
for (size_t i = 0; i < v.size(); i++) {
cout << " " << v[i];
}
cout << endl;
}
int main() {
int a[] = {1, 2, 3, 4, 5, 6};
vector<int> v(a, a + 6);
reverse(v.begin(), v.end());
show("reverse: ", v);
vector<int> sq(v.size()); // destination must have room
transform(v.begin(), v.end(), sq.begin(), square);
show("squares: ", sq);
replace(v.begin(), v.end(), 3, 30); // every 3 becomes 30
show("replace: ", v);
vector<int> c(3);
copy(v.begin(), v.begin() + 3, c.begin());
show("copy 3: ", c);
fill(c.begin(), c.end(), 0);
show("fill 0: ", c);
rotate(v.begin(), v.begin() + 2, v.end()); // element 2 becomes the first
show("rotate 2: ", v);
return 0;
}Output:
reverse: 6 5 4 3 2 1
squares: 36 25 16 9 4 1
replace: 6 5 4 30 2 1
copy 3: 6 5 4
fill 0: 0 0 0
rotate 2: 4 30 2 1 6 5remove does not really remove
Because an algorithm cannot change a container's size, remove(first, last, value) only moves the kept elements to the front and returns an iterator to the new logical end. The container's erase member must then cut off the leftovers. This pair is called the erase-remove idiom:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int a[] = {4, 0, 7, 0, 0, 9};
vector<int> v(a, a + 6);
vector<int>::iterator newEnd = remove(v.begin(), v.end(), 0);
cout << "size after remove: " << v.size() << endl; // still 6
v.erase(newEnd, v.end()); // really shrink it
cout << "size after erase: " << v.size() << endl;
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}Output:
size after remove: 6
size after erase: 3
4 7 9 5. Sorting and Searching
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool descending(int x, int y) {
return x > y;
} // comparison function
int main() {
int a[] = {42, 17, 8, 99, 23, 4};
vector<int> v(a, a + 6);
sort(v.begin(), v.end()); // ascending (uses <)
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
// binary_search, lower_bound need a SORTED range
cout << "23 present? " << binary_search(v.begin(), v.end(), 23) << endl;
cout << "50 present? " << binary_search(v.begin(), v.end(), 50) << endl;
vector<int>::iterator pos = lower_bound(v.begin(), v.end(), 20);
cout << "first element >= 20 is " << *pos << " at index " << (pos - v.begin()) << endl;
sort(v.begin(), v.end(), descending); // custom order
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
sort(a, a + 6); // works on a plain array too
cout << "array sorted: " << a[0] << " ... " << a[5] << endl;
return 0;
}Output:
4 8 17 23 42 99
23 present? 1
50 present? 0
first element >= 20 is 23 at index 3
99 42 23 17 8 4
array sorted: 4 ... 99Set and numeric algorithms
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
using namespace std;
int main() {
int a[] = {1, 3, 5, 7, 9};
int b[] = {3, 4, 5, 6, 7};
vector<int> u, in;
set_union(a, a + 5, b, b + 5, back_inserter(u)); // back_inserter grows u
set_intersection(a, a + 5, b, b + 5, back_inserter(in));
cout << "union: ";
copy(u.begin(), u.end(), ostream_iterator<int>(cout, " "));
cout << endl << "intersection: ";
copy(in.begin(), in.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << "sum of a = " << accumulate(a, a + 5, 0) << endl; // 0 is the start value
cout << "a . b = " << inner_product(a, a + 5, b, 0) << endl; // 1*3 + 3*4 + ...
return 0;
}Output:
union: 1 3 4 5 6 7 9
intersection: 3 5 7
sum of a = 25
a . b = 145back_inserter(u) is an insert iterator: writing through it calls u.push_back(), so the algorithm can add elements without knowing about the container.
6. Function Objects (Functors)
A function object (or functor) is an object of a class that overloads the function call operator operator(). It can be called just like a function: f(x). Algorithms accept either a function pointer or a function object.
class Square {
public:
int operator()(int x) const {
return x * x;
} // makes Square objects callable
};
Square sq;
int y = sq(5); // calls sq.operator()(5): y = 25Why use a function object instead of a function?
- It can hold state. A functor has data members, so it can carry a value (a threshold, a counter, a running total) between calls. An ordinary function can only do that with global variables.
- It can be configured through its constructor:
GreaterThan(50)andGreaterThan(80)are two differently-behaving objects of one class. - It is often faster: the call to
operator()is known at compile time and can be inlined, whereas a call through a function pointer usually cannot. - It has a type, so it can be used as a template argument, e.g. the comparator of
set<int, greater<int> >orpriority_queue.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class GreaterThan { // a configurable predicate
int limit;
public:
GreaterThan(int l) {
limit = l;
}
bool operator()(int x) const {
return x > limit;
}
};
class Accumulator { // a functor with state
public:
int total, items;
Accumulator() {
total = 0;
items = 0;
}
void operator()(int x) {
total = total + x;
items++;
}
};
int main() {
int m[] = {45, 82, 67, 91, 38, 74};
vector<int> marks(m, m + 6);
cout << "above 60: " << count_if(marks.begin(), marks.end(), GreaterThan(60)) << endl;
cout << "above 80: " << count_if(marks.begin(), marks.end(), GreaterThan(80)) << endl;
Accumulator acc =
for_each(marks.begin(), marks.end(), Accumulator()); // for_each returns the functor
cout << "total " << acc.total << " of " << acc.items << " students, average "
<< acc.total / acc.items << endl;
return 0;
}Output:
above 60: 4
above 80: 2
total 397 of 6 students, average 66Predefined function objects (<functional>)
| Type | Function objects | Meaning |
|---|---|---|
| Arithmetic | plus<T>, minus<T>, multiplies<T>, divides<T>, modulus<T>, negate<T> | x + y, x - y, ... -x |
| Relational | equal_to<T>, not_equal_to<T>, greater<T>, greater_equal<T>, less<T>, less_equal<T> | x == y, x != y, x > y, ... |
| Logical | logical_and<T>, logical_or<T>, logical_not<T> | x && y, x or y, !x |
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <set>
using namespace std;
int main() {
int a[] = {5, 1, 4, 2, 3};
vector<int> v(a, a + 5);
sort(v.begin(), v.end(), greater<int>()); // descending
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
cout << "product = " << accumulate(v.begin(), v.end(), 1, multiplies<int>()) << endl;
int b[] = {10, 20, 30, 40, 50};
vector<int> sum(5);
transform(v.begin(), v.end(), b, sum.begin(), plus<int>()); // element-wise addition
for (size_t i = 0; i < sum.size(); i++) {
cout << sum[i] << " ";
}
cout << endl;
set<int, greater<int> > s(a, a + 5); // a set kept in descending order
cout << "set: ";
for (set<int, greater<int> >::iterator it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}Output:
5 4 3 2 1
product = 120
15 24 33 42 51
set: 5 4 3 2 1 Sorting objects with a function object
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Employee {
string name;
double salary;
Employee(string n, double s) {
name = n;
salary = s;
}
};
class BySalary {
public:
bool operator()(const Employee& x, const Employee& y) const {
return x.salary > y.salary; // highest salary first
}
};
class ByName {
public:
bool operator()(const Employee& x, const Employee& y) const {
return x.name < y.name;
}
};
void list(const vector<Employee>& e) {
for (size_t i = 0; i < e.size(); i++) {
cout << " " << e[i].name << " " << e[i].salary << endl;
}
}
int main() {
vector<Employee> staff;
staff.push_back(Employee("Nikhil", 52000));
staff.push_back(Employee("Ayesha", 48000));
staff.push_back(Employee("Tara", 61000));
sort(staff.begin(), staff.end(), BySalary());
cout << "by salary:" << endl;
list(staff);
sort(staff.begin(), staff.end(), ByName());
cout << "by name:" << endl;
list(staff);
return 0;
}Output:
by salary:
Tara 61000
Nikhil 52000
Ayesha 48000
by name:
Ayesha 48000
Nikhil 52000
Tara 61000The same data is sorted two ways just by passing a different function object. Instead of a functor, the class could define operator<, which sort uses by default.
Key points to remember
- Algorithms are function templates that work on iterator ranges
[first, last); they never change a container's size. - Categories: non-mutating (
find,count,for_each), mutating (copy,transform,replace,reverse,remove), sorting/searching (sort,binary_search,lower_bound), set, heap, numeric (accumulate). remove+erase(erase-remove idiom) really deletes elements.binary_search,lower_boundand the set algorithms need a sorted range.- A function object is an object of a class with
operator(); it can keep state, be configured, be inlined, and be used as a template argument. - Predefined functors in
<functional>:plus,minus,multiplies,greater,less,equal_to,logical_and, ...
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What are STL algorithms? Classify them with examples. (10 Marks)
- Write: the definition (function templates on iterator ranges), the categories table, and two programs (non-mutating and sorting/searching) with output.
- Q2. What is a function object? How is it different from a function? Write a program. (10 Marks)
- Write: the definition with
operator(), the four reasons, theGreaterThan/Accumulatorprogram, and the predefined function objects table. - Q3. Write a program to sort a vector of objects using a function object. (5 Marks)
- Write: the
Employeeprogram. - Q4. Explain
sort(),find(),count()andbinary_search()with syntax. (5 Marks) - Q5. Why must
remove()be followed byerase()? (2.5 Marks)