C++ Algorithms and Iterators
The header <algorithm> has ready functions which work on ranges described by iterators. An iterator is like a pointer to an item of a container. begin() is the first and end() is one after the last.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v = {5, 2, 9, 1, 7, 2};
std::sort(v.begin(), v.end());
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
std::cout << std::count(v.begin(), v.end(), 2) << '\n';
std::cout << *std::min_element(v.begin(), v.end()) << ' ' << *std::max_element(v.begin(), v.end()) << '\n';
std::cout << std::accumulate(v.begin(), v.end(), 0) << '\n';
std::cout << std::binary_search(v.begin(), v.end(), 7) << '\n'; // needs a sorted range
auto it = std::find(v.begin(), v.end(), 9);
if (it != v.end()) std::cout << "found at index " << it - v.begin() << '\n';
}
Output
1 2 2 5 7 9
2
1 9
26
1
found at index 5
transform, for_each and custom rules
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> squares(v.size());
std::transform(v.begin(), v.end(), squares.begin(), [](int n) { return n * n; });
for (int x : squares) std::cout << x << ' ';
std::cout << '\n';
std::vector<std::string> names = {"Meera", "Al", "Riya", "Karan"};
std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {
return a.size() < b.size();
});
for (const auto& n : names) std::cout << n << ' ';
std::cout << '\n';
}
Output
1 4 9 16
Al Riya Meera Karan
Remove items: the erase-remove idiom
std::remove_if only moves the unwanted items to the end. You must call erase too. In C++20 there is std::erase_if, which does both:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
std::erase_if(v, [](int n) { return n % 2 == 0; });
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
}
Output
1 3 5
Iterator loop
#include <iostream>
#include <list>
int main() {
std::list<char> letters = {'a', 'b', 'c'};
for (auto it = letters.begin(); it != letters.end(); ++it) {
std::cout << *it;
}
std::cout << '\n';
}
Output
abc
Note:
Before you write a loop, check if an STL algorithm already does the job. The names say what the code does. Next: C++ Lambda Expressions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |