The C++ Standard Template Library Non-Modifying Algorithms – Part 7

C++ STL Non-Modifying Algorithms

Welcome again to the seventh part of our continuing series on the C++ Standard Template Library. This chapter comes after a couple of months after part six where we looked at the introduction to algorithms as we also touched on Iterators. Today we will be taking a brief look at non-modifying algorithms.

Again if you have missed the entirety of this series and are not familiar with the C++ STL then I would recommend you go back to the beginning and follow through on the entire series starting with the overview here.

Why Use Non-Modifying Algorithms

The simple answer is because they give you the stability, efficiency, security and the simplicity you get out of using the STL while programming.

It is good practice to use the C++ STL wherever possible in your code. The library is very mature, efficient and safe and therefore you need to give priority to STL wherever there is an STL solution to the problem you are trying to solve. The same is true with other libraries and that is exactly what a library is there for in the first place.

Read Also  GPU Technology Conference on Track

What are Non-Modifying Algorithms?

These are basically algorithms that do not modify the data on which they operate on. In other terms, they are read-only functions that return a value based on a read and check on the underlying data. For instance, you could have a function that simply counts elements or you might want to know the greatest element in a range.

There are several ways to accomplish the trivial tasks mentioned above. You could write your own function or go with existing algorithms. Of course, the ideal choice here should be algorithms and there is just one simple way to get you familiar with them. The best way to illustrate this, of course, is through some examples.

We will illustrate the use of a few non-modifying algorithms then leave you to brush through the C++ documentation to get the list of algorithms at your fingertips.

Counting Algorithm

Assuming we want to get the number of times a certain value appears in an array. This example would accomplish that:

How about Getting the Maximums and Minimums from an array

We start off by getting the highest value in the array

Read Also  Time for the TIOBE August 2017 Programming Languages Review

Likewise, we can find the smallest value in the array:

How about getting the maximum and minimum values in an array in a single statement.

That’s it for this part. All other non-modifying algorithms work in a simple and consistent manner as those illustrated here. In the next chapter of this C++ STL series, we will be taking a brief look at the modifying algorithms in part 8 of the Standard Template Library tutorial series. We will focus more on showing illustrations of how they work within the C++ Standard Template Libraries.