Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 5 - Using algorithms

12/19/2016

Here we will go over basic usages of the algorithms library. To use the algorithms library, we have to write #include <algorithm> at the top of the file.

#include <algorithm>
#include <cstdio>

using namespace std;

int main() {
    /* Visual Studio: */ getchar();
    return 0;
}

Algorithms allow us to do various operations over lists in our code. So we will include <vector> and create a vector of ints with the values 11, 23, and 17.

#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

int main() {
    vector<int> list;
    list.push_back(11);
    list.push_back(23);
    list.push_back(17);

    /* Visual Studio: */ getchar();
    return 0;
}

Now that we have a list of elements, we will print them out. To do so we have to use an algorithm -- for_each. To use for_each we have to define a function for what to do with each element. In this case we will print out each element with a space after it:

#include <algorithm>
#include <cstdio>
#include <iostream> // <-- required to use cout and cin
#include <vector>

using namespace std;

void print_element(int element) {
    cout << element << " ";
}

int main() {
    vector<int> list;
    list.push_back(11);
    list.push_back(23);
    list.push_back(17);
    for_each(list.begin(), list.end(), print_element);

    /* Visual Studio: */ getchar();
    return 0;
}

The for_each statement will now go from the beginning to the end of the list, applying print_element to each element.

print_element is a function that takes one parameter -- an int that we name element. It returns void, the lack of a value. What the function does is defined inside the curly brackets. It prints out the element and a space.

Having to separate the operation into a function makes it harder to read our code. To fix this, we can put the function body in place of the name of the function:

    for_each(list.begin(), list.end(),
             [](int element) {
                 cout << element << " ";
             });

This makes it clear what we intend to do.

There are other algorithms that allow us to express what we intend to do directly. Let's use sort to sort the list:

    sort(list.begin(), list.end());

This will sort the list into ascending order. The new contents will be 11, 17, and 23, in that order.