Learning C++: Nonmutating Algorithms of the STL Part 2

Mike McMillan
Level Up Coding
Published in
8 min readApr 22, 2020

Photo by Kevin Ku on Unsplash

In this article, I’ll present another set of nonmutating algorithms found in the C++’s Standard Template Library. This set of functions are functions you can use to find data or to search for data in a container. Before I begin, I should mention that these functions are to be used with unsorted data. I’ll talk more about which functions to use with sorted data in another article.

The find Function

The find function is used to determine if a specified value exists in a container. The function returns an iterator to the found value if the value is in the container and the function returns end if the value is not found in the container.

Here is the syntax template for the find function:

find(range-start, range-end, value);

Here is an example program using the find function:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
void buildVec(vector<int> &vec, int n) {
srand(time(0));
for (int i = 1; i <= n; i++) {
vec.push_back(rand() % 100 + 1);
}
}
void printVec(vector<int> vec) {
int i = 0;
for (const int n : vec) {
cout << n << " ";
if (++i % 10 == 0) {
cout << endl;
}
}
}
int main () {
vector<int> numbers;
buildVec(numbers, 50);
printVec(numbers);
cout << endl;
int value;
for (int i = 1; i <= 2; i++) {
cout << "Value to find: ";
cin >> value;
auto position = find(numbers.begin(), numbers.end(), value);
if (position != numbers.end()) {
cout << "Found " << value << "." << endl;
}
else {
cout << value << " not in numbers." << endl;
}
}
return 0;
}

Here is the output from one run of this program:

57 4 86 1 39 47 67 37 12 30
86 6 94 48 23 72 82 31 82 52
65 29 60 68 48 18 29 2 97 74
87 23 68 61 45 10 85 55 94 72
34 61 44 45 43 5 12 15 24 54
Value to find: 3
3 not in numbers.
Value to find: 82
Found 82.

The find_if Function

The find_if function is used to find a value based on a predicate function, which can be a lambda function or a…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Written by Mike McMillan

Mike McMillan writes about computer programming and running. See more of his writing and courses at https://mmcmillan.gumroad.com.

No responses yet

Write a response