The C++ Standard Library algorithms are components that perform algorithmic operations on containers and other sequences.

Because searching, counting, and sorting are such common operations, the C++ Standard Library comes with a set of algorithms to easily implement these common functions in just a few lines of code. The Standard Library functions are well tested, optimized and efficient. They work on a variety of different container types, and many support parallelization (large problems can be divided into smaller ones and solved simultaneously, in order to complete tasks faster).

The algorithms library functions operate on ranges of elements. Note that a range is defined as [first, last) where last refers to the element past the last element to inspect.

The C++ Standard algorithms are located in the <algorithm> header.

C++ algorithms for non-modifying sequence operations

Defined in header <algorithm>

std::all_of, std::any_of and std::none_of

Checks and returns true if a predicate is true for all, any or none of the elements in a range, else returns false.

An example of using std::all_of, std::any_of and std::none_of:

#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <functional>

int main()
{
std::vector<int>v{ 0, 2, 4, 12, 14, 48, 12, 20 };

std::cout << "Among the numbers: ";
std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';

// std::all_of
if (std::all_of(v.cbegin(), v.cend(), [](int i) { return i % 2 == 0; })) {
    std::cout << "All numbers are even\n";
}

// std::none_of
if (std::none_of(v.cbegin(), v.cend(), std::bind(std::modulus<int>(), std::placeholders::_1, 2))) {
    std::cout << "None of them are odd\n";
}

struct DivisibleBy
{
    const int d;
    DivisibleBy(int n) : d(n) {}
    bool operator()(int n) const { return n % d == 0; }
};

// std::any_of
if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) {
    std::cout << "At least one number is divisible by 7\n";
}


return 0;
}

Output:

Among the numbers: 0 2 4 12 14 48 12 20
All numbers are even
None of them are odd
At least one number is divisible by 7

std::for_each

Applies a function to a range of elements. std::for_each takes a range of elements as input and applies a custom function to every element. This is useful when you want to perform the same operation to every element in a list. std::for_each guarantees sequential execution.

An example of using std::for_each:

#include <vector>
#include <algorithm>
#include <iostream>

struct Sum
{
void operator()(int n) { sum += n; }
int sum{ 0 };
};

int main()
{
std::vector<int>v{ 0, 2, 4, 12, 14, 48, 12, 20 };

auto print = [](const int& n) { std::cout << " " << n; };

std::cout << "before:";
std::for_each(v.cbegin(), v.cend(), print);
std::cout << '\n';

std::for_each(v.begin(), v.end(), [](int& n) { n++; });

// calls Sum::operator() for each number
Sum s = std::for_each(v.begin(), v.end(), Sum());

std::cout << "after: ";
std::for_each(v.cbegin(), v.cend(), print);
std::cout << '\n';
std::cout << "sum: " << s.sum << '\n';

return 0;
}

Output:

before: 0 2 4 12 14 48 12 20
after:  1 3 5 13 15 49 13 21
sum: 120

std::count and std::count_if

Returns the number of elements satisfying specific criteria.

An example of using std::count and std::count_if:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };

// determine how many integers in a std::vector match a target value.
int target1 = 3;
int target2 = 5;
int num_items1 = std::count(v.begin(), v.end(), target1);
int num_items2 = std::count(v.begin(), v.end(), target2);
std::cout << "number: " << target1 << " count: " << num_items1 << '\n';
std::cout << "number: " << target2 << " count: " << num_items2 << '\n';

// using a lambda expression to count elements divisible by 3.
int num_items3 = std::count_if(v.begin(), v.end(), [](int i) {return i % 3 == 0; });
std::cout << "numbers divisible by three: " << num_items3 << '\n';

return 0;
}

Output:

number: 3 count: 2
number: 5 count: 0
numbers divisible by three: 3

std::find

Searches for the first occurrence of a value in a container. std::find takes 3 parameters: an iterator to the starting element in the sequence, an iterator to the ending element in the sequence, and a value to search for. It returns an iterator pointing to the element (if it is found) or the end of the container (if the element is not found).

std::find_if

Finds an element in a range. Returns an iterator to the first element in the range [first,last) for which predicate returns true. If no such element is found, the function returns last.

std::find_if_not

Finds an element in a range (negative condition). Returns an iterator to the first element in the range [first,last) for which predicate returns false. If no such element is found, the function returns last.

An example of using std::find, std::find_if and std::find_if_not:

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

bool IsOdd(int i) {
return ((i % 2) == 1);
}

int main()
{

int n1 = 3;
std::vector<int> v{ 0, 1, 2, 3, 4 };
auto result = std::find(std::begin(v), std::end(v), n1);

if (result != std::end(v)) {
    std::cout << "v contains: " << n1 << '\n';
}
else {
    std::cout << "v does not contain: " << n1 << '\n';
}

auto it_if = std::find_if(v.begin(), v.end(), IsOdd);
std::cout << "First odd value is " << *it_if << '\n';

// Using a lambda 
auto it_if_not =
    std::find_if_not(v.begin(), v.end(), [](int i) {return i % 2; });
std::cout << "First even value is " << *it_if_not << '\n';
return 0;
}

Output:

v contains: 3
First odd value is 1
First even value is 0

Another example of using std::find_if:

#include <algorithm>
#include <array>
#include <iostream>
#include <string_view>

// containsNuts will return true if the element matches
bool containsNut(std::string_view str)
{
// std::string_view::find returns std::string_view::npos if it doesn't find
// the substring. Otherwise it returns the index where the substring occurs
// in str.
return (str.find("nuts") != std::string_view::npos);
}

int main()
{
std::array<std::string_view, 4> arr{ "apples", "bananas", "peanuts", "walnuts" };

// Scan our array to see if any elements contain the "nuts" substring
auto found{ std::find_if(arr.begin(), arr.end(), containsNut) };

if (found == arr.end())
{
    std::cout << "No nuts\n";
}
else
{
    std::cout << "Found " << *found << '\n';
}
return 0;
}

Output:

Found peanuts

std::find_first_of

Searches for any one of a set of elements.

An example of using std::find_first_of:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
std::vector<int> v{ 0, 2, 3, 25, 5 };
const auto t = { 3, 19, 10, 34 };

auto result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end());

if (result == v.end()) {
    std::cout << "No elements of v were equal to 3, 19, 10 or 34\n";
}
else {
    std::cout << "Found a match at index: "
        << std::distance(v.begin(), result) << "\n";
}

return 0;
}

Output:

 Found a match at index: 2

std::search

Searches range for sub-sequence. Searches the range [first1,last1] for the first occurrence of the sequence defined by [first2,last2], and returns an iterator to its first element, or last1 if no occurrences are found.

An example of using std::search:

#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>

template <typename Container>
bool in_quote(const Container& cont, const std::string& s)
{
return std::search(cont.begin(), cont.end(), s.begin(), s.end()) != cont.end();
}

int main()
{
std::string str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
// str.find() can be used as well
std::cout << "The string \"ipsum\" is found: " << std::boolalpha << in_quote(str, "ipsum") << '\n';
std::cout << "The string \"magna\" is found: " << in_quote(str, "magna") << '\n';


// C++17 overload example:
std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
    " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
std::string needle = "consectetur";
auto it = std::search(in.begin(), in.end(),
    std::boyer_moore_searcher(
        needle.begin(), needle.end()));
if (it != in.end()) {
    std::cout << "The string \"" << needle << "\" is found at offset "
        << it - in.begin() << '\n';

}
else {
    std::cout << "The string \"" << needle << "\" is not found.\n";

}

return 0;
}

Output:

The string "ipsum" is found: true
The string "magna" is found: false
The string "consectetur" is found at offset 28

Learn more about C++ programming services.

Related services: C++ Software Development

References: