C++11 has a bunch of new cool algorithms in <algorithm>
header. C++14 has even more algorithms. If you're stuck with the pre-C++11 compiler, you have to write those from scratch. For example, if you wish to output characters from 65 to 125 code points, you have to write the following code on a pre-C++11 compiler:
#include <boost/array.hpp> boost::array<unsigned char, 60> chars_65_125_pre11() { boost::array<unsigned char, 60> res; const unsigned char offset = 65; for (std::size_t i = 0; i < res.size(); ++i) { res[i] = i + offset; } return res; }
Basic knowledge of C++ is required for this recipe along with basic knowledge of Boost.Array
library.
The Boost.Algorithm
library has all the new C++11 and C++14 algorithms. Using it, you can rewrite the previous example in the following manner:
#include <boost/algorithm/cxx11/iota.hpp> #include <boost/array.hpp> boost::array<unsigned char, 60> chars_65_125() { boost::array<unsigned char, 60> res; boost::algorithm::iota(res.begin(), res.end(), 65); return res; }
As you are probably aware, Boost.Algorithm
has a header file for each algorithm. Just include the header file and use the required function.
It's boring to have a library that just implements algorithms from C++ standard. That's not innovative; that's not the Boost way! That's why you can find in Boost.Algorithm
, functions that are not part of C++. Here, for example, is a function that converts input into hexadecimal representation:
#include <boost/algorithm/hex.hpp> #include <iterator> #include <iostream> void to_hex_test1() { const std::string data = "Hello word"; boost::algorithm::hex( data.begin(), data.end(), std::ostream_iterator<char>(std::cout) ); }
The preceding code outputs the following:
48656C6C6F20776F7264
What's more interesting, all the functions have additional overloads that accept a range as a first parameter instead of two iterators. Range is a concept from Ranges TS. Arrays and containers that have .begin()
and .end()
functions satisfy the range concept. With that knowledge the previous example could be shortened:
#include <boost/algorithm/hex.hpp> #include <iterator> #include <iostream> void to_hex_test2() { const std::string data = "Hello word"; boost::algorithm::hex( data, std::ostream_iterator<char>(std::cout) ); }
C++17 will have searching algorithms from Boost.Algorithm
. Boost.Algorithm
library will be soon extended with new algorithms and C++20 features like constexpr usable algorithms. Keep an eye on that library, as some day, it may get an out-of-the-box solution for a problem that you're dealing with.
- Official documentation for
Boost.Algorithm
contains a full list of functions and short descriptions for them at http://boost.org/libs/algorithm - Experiment with new algorithms online: http://apolukhin.github.io/Boost-Cookbook