Boost
Boost
#boost
Table of Contents
About 1
Remarks 2
What is Boost? 2
Versions 3
Examples 5
Installation or Setup 5
Examples 9
Examples 11
Introduction 12
Examples 12
Examples 14
Basic Usage 14
Error Handling 14
Default Values 15
Switches 16
Remarks 17
Examples 17
boost::split() 17
Replace Algrorithms 18
boost::replace_all(): 18
boost::replace_first(): 18
boost_replace_last(): 19
to_upper(): 19
to_lower(): 20
Examples 21
Credits 23
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: boost
It is an unofficial and free boost ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official boost.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with boost
Remarks
What is Boost?
Boost is a large collection of free, high quality C++ libraries that cover a broad range of topics. It is
often considered a "second standard library" for C++, since many common problems in C++ are
solved by using Boost.
From boost.org:
We emphasize libraries that work well with the C++ Standard Library. Boost libraries
are intended to be widely useful, and usable across a broad spectrum of applications.
The Boost license encourages both commercial and non-commercial use.
Some Boost libraries have even made their way into the C++11 standard library, and some other,
such as Boost.Optional and Boost.Variant, will be a part of C++17.
Boost covers most corners of programming. From the boost tag wiki here on Stack Overflow:
https://riptutorial.com/ 2
• Broken compiler workarounds
Versions
1.13.0 Utility, Type Traits, Call Traits, Compressed Pair notes 2000-02-29
https://riptutorial.com/ 3
Version New Libraries Release Notes Release Date
Algorithm, Functional/OverloadedFunction,
1.50.0 notes 2012-06-28
LocalFunction, Utility/IdentityType
https://riptutorial.com/ 4
Version New Libraries Release Notes Release Date
Examples
Installation or Setup
Most of the Boost libraries are header-only, meaning that there's nothing you have to compile or
link to.
Make sure you are getting the most recent version of Boost:
1. Visit www.boost.org
2. Look for the Current Release download. Currently, this links here.
https://riptutorial.com/ 5
3. Select the appropriate archive file for your operating system, and download.
Header-only libraries can then be used by simply including the respective header files.
• Boost.Chrono
• Boost.Context
• Boost.Filesystem
• Boost.GraphParallel
• Boost.IOStreams
• Boost.Locale
• Boost.MPI
• Boost.ProgramOptions
• Boost.Python
• Boost.Regex
• Boost.Serialization
• Boost.Signals
• Boost.System
• Boost.Thread
• Boost.Timer
• Boost.Wave
• Boost.DateTime
• Boost.Graph
• Boost.Math
• Boost.Random
• Boost.Test
https://riptutorial.com/ 6
• Boost.Exception
The source for Boost can be obtained through the download link on the site, which will re-direct to
its SourceForge page for the latest version (1.61.0 as of July 2016). This can be unzipped (or un-
tared, etc) to a directory (such as C:\local\boost_1_61_0). This directory can then be added to the
include path for the software you are building. After this, you can include Boost headers in C++
files with #include <boost/header/path.hpp>.
The majority of the libraries in Boost are header-only. If you only need these then the above
source distribution is all that is needed. However, if you need to use one of the libraries that
requires a compiled binary to be built, you will need that as well.
On any system, the most reliable way to get the correct binaries is to build them yourself. These
directions are somewhat different for Windows or Linux/Unix/POSIX.
On Windows with Visual Studio, an alternative to building the libraries yourself is to download pre-
built libraries from Boost's SourceForge page (1.61.0 as of July 2016). On that page you can
select an installer that will install a version for a specific Visual Studio build or the 7-zip file
(boost_X_XX_X-bin-all-32-64.7z) that contains the binaries for all the supported Visual Studio
versions. Either of these options includes the source/headers as well as the binaries, so there is
no need to have downloaded the source distribution above. Once you have it, extract/install to a
directory (such as C:\local\boost_1_61_0) and add that directory to your include path, then add the
directory containing the binaries that correspond to your version of Visual Studio (e.g.
C:\local\boost_1_61_0\lib32-msvc-12.0 for Visual Studio 2013 32-bit projects) to the library path.
First, install boost from the Cygwin mirror: open the install exe, search for boost, install the
packages.
After boost is installed: it will be located in /usr/include/boost. This is where everything is. All
#include statements will be a path from the boost folder, as in: #include
<boost/archive/text_oarchive.hpp>.
Once you include the boost files of your choice in your .cpp files, your code will still not compile in
your IDE of choice until you link the libraries and tell cmake to search for your downloaded boost
code.
# for example:
find_package(Boost 1.60.0 COMPONENTS serialization)
https://riptutorial.com/ 7
Then, include the directories: include_directories(${Boost_INCLUDE_DIRS})
add_executable(your_target ${SOURCE_FILES})
target_link_libraries(your_target ${Boost_LIBRARIES} -any_missing_boostlibs)
Before starting your program, avoid an error dump by testing to see if boost has been found before
including anything or running your code:
if (Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(YourTarget ${SOURCE_FILES})
target_link_libraries(your_target ${Boost_LIBRARIES} -missing_libs)
endif()
I included -missing_libs because an error you may run into is that some boost library or another
might not have been linked, and you must manually add it--for instance, the link I referenced
earlier.
cmake_minimum_required(VERSION 3.7)
project(your_project)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(your_project ${SOURCE_FILES})
target_link_libraries(your_project ${Boost_LIBRARIES})
endif()
https://riptutorial.com/ 8
Chapter 2: Async boost::process
Examples
Using all 3 pipes of a child process asynchronously.
#include <vector>
#include <string>
#include <boost/process.hpp>
#include <boost/asio.hpp>
#include <boost/process/windows.hpp>
int Run(
const std::string& exeName, ///< could also be UTF-16 for Windows
const std::string& args, ///< could also be UTF-16 for Windows
const std::string& input, ///< [in] data for stdin
std::string& output, ///< [out] data from stdout
std::string& error ///< [out] data from stderr
)
{
using namespace boost;
asio::io_service ios;
// stdout setup
//
std::vector<char> vOut(128 << 10); // that worked well for my decoding app.
auto outBuffer{ asio::buffer(vOut) };
process::async_pipe pipeOut(ios);
// stderr setup
//
std::vector<char> vErr(128 << 10);
auto errBuffer{ asio::buffer(vErr) };
process::async_pipe pipeErr(ios);
https://riptutorial.com/ 9
// stdin setup
//
auto inBuffer{ asio::buffer(input) };
process::async_pipe pipeIn(ios);
process::child c(
exeName + " " + args, // exeName must be full path
process::std_out > pipeOut,
process::std_err > pipeErr,
process::std_in < pipeIn
);
asio::async_write(pipeIn, inBuffer,
[&](const system::error_code & ec, std::size_t n)
{
pipeIn.async_close(); // tells the child we have no more data
});
ios.run();
c.wait();
return c.exit_code(); // return the process' exit code.
}
There is a bug/fix for boost 1.64, the bug only affects Windows, apparently.
~async_pipe()
{
//fix
//if (_sink .native() != ::boost::detail::winapi::INVALID_HANDLE_VALUE_)
// ::boost::detail::winapi::CloseHandle(_sink.native());
//if (_source.native() != ::boost::detail::winapi::INVALID_HANDLE_VALUE_)
// ::boost::detail::winapi::CloseHandle(_source.native());
boost::system::error_code ec;
close(ec);
//fix
}
https://riptutorial.com/ 10
Chapter 3: Boost Accumulators Framework
Examples
Computing mean and variance
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
int main()
{
using namespace boost::accumulators;
accumulator_set<int, stats<tag::mean, tag::variance>> acc;
std::cout << "mean=" << mean(acc) << ", variance=" << variance(acc) << '\n';
// prints "mean=3.5, variance=2.91667"
return 0;
}
https://riptutorial.com/ 11
Chapter 4: BOOST- Compare Images using
OpevCV
Introduction
This documentation explains how an external Image can be tested and compared with the output
image of OpenCV. For example, To compare two blurred images and test if they both are same,
we blur an original image in an external software (I used WiT Image Processing software) or just
download any blurred image online- output1. Create a Win32 OpenCV project in Visual Studio.
Read the original image as an input to the OpenCV. Blur the original image in OpenCV and
compare with output1.
Examples
OpenCV code to read Images and compare
imshow("witout", witout);
imshow("cvout", cvout);
https://riptutorial.com/ 12
Read BOOST- Compare Images using OpevCV online:
https://riptutorial.com/boost/topic/10703/boost--compare-images-using-opevcv
https://riptutorial.com/ 13
Chapter 5: Boost Program Options
Examples
Basic Usage
Boost program options provides a simple and safe way to parse and handle command line
arguments.
#include <boost/program_options.hpp>
#include <string>
#include <iostream>
po::variables_map vm;
po::options_description desc("Allowed Options");
// declare arguments
desc.add_options()
("name", po::value<std::string>()->required(), "Type your name to be greeted!");
return 0;
}
would produce:
Allowed Options:
--name arg Type your name to be greeted!
Error Handling
https://riptutorial.com/ 14
#include <boost/program_options.hpp>
#include <string>
#include <iostream>
po::variables_map vm;
po::options_description desc("Allowed Options");
// declare options
desc.add_options()
("name", po::value<std::string>()->required(), "Type your name to be greeted!");
// parse arguments
po::store(po::parse_command_line(argc, argv, desc), vm);
// check arguments
try {
po::notify(vm);
} catch (std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
std::cout << desc << std::endl;
return 1;
}
// program logic
std::cout << "Hello " << vm["name"].as<std::string>() << std::endl;
return 0;
}
$ ./a.out
Error: the option '--name' is required but missing
Allowed Options:
--name arg Type your name to be greeted!
Default Values
// declare options
desc.add_options()
("name", po::value<std::string>()->required(), "Type your name to be greeted!")
("rank", po::value<std::string>()->default_value("Dark Knight"), "Your rank");
std::cout << "Hello " << vm["name"].as<std::string>() << " " << vm["rank"].as<std::string>()
<< std::endl;
https://riptutorial.com/ 15
$ ./a.out
Error: the option '--name' is required but missing
Allowed Options:
--name arg Type your name to be greeted!
--rank arg (=Dark Knight) Your rank
Switches
A switch is a command line argument which takes no value. It can be specified with:
desc.add_options()
("hidden", po::bool_switch()->default_value(false), "Hide your name");
if (vm["hidden"].as<bool>())
std::cout << "Hello *****" << std::endl;
Allowed Options:
--name arg Type your name to be greeted!
--rank arg (=Dark Knight) Your rank
--hidden Hide your name
https://riptutorial.com/ 16
Chapter 6: boost String Algorithms Library
Remarks
Boost Documention on String Algrorithms
Examples
boost::split()
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
// String to split
// Line container
vector<string> lines;
// Splits string
cin.get();
return 0;
}
Declare string str and set it to "You're supposed to see this!|NOT THIS!!!!!!".
https://riptutorial.com/ 17
Get input.
Replace Algrorithms
boost::replace_all():
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
// Print str
cin.get();
return 0;
}
boost::replace_first():
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
// Print str
https://riptutorial.com/ 18
cout << str.c_str() << endl;
cin.get();
return 0;
}
boost_replace_last():
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
// Print str
cin.get();
return 0;
}
to_upper():
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
https://riptutorial.com/ 19
string str = "ThIS iS SUpPoSEd tO Be UpPeR CAsE.";
boost::to_upper(str);
// Print str
cin.get();
return 0;
}
to_lower():
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
boost::to_lower(str);
// Print str
cin.get();
return 0;
}
https://riptutorial.com/ 20
Chapter 7: Using boost.python
Examples
Introductory Example on Boost.Python
Things are easy when you have to use a C++ library in a Python project. Just you can use Boost.
Let's start with a small C++ file. Our C++ project has only one method which returns some string
"This is the first try". Call it CppProject.cpp
BOOST_PYTHON_MODULE(CppProject) {
boost::python::def("getTryString", firstMethod); // boost::python is the namespace
}
cmake_minimum_required(VERSION 2.8.3)
FIND_PACKAGE(PythonInterp)
FIND_PACKAGE(PythonLibs)
FIND_PACKAGE(Boost COMPONENTS python)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})
PYTHON_ADD_MODULE(NativeLib CppProject)
FILE(COPY MyProject.py DESTINATION .) # See the whole tutorial to understand this line
By this part of the tutorial everything is so easy. you can import the library and call method in your
python project. Call your python project MyProject.py.
import NativeLib
print (NativeLib.getTryString)
https://riptutorial.com/ 21
• python MyProject.py. Now, you have to see the string which the method in your C++ project
returns.
std::vector<float> secondMethod() {
return std::vector<float>();
}
BOOST_PYTHON_MODULE(CppProject) {
boost::python::def("getEmptyVec", secondMethod);
}
then when the functions gets called Python will tell you No to_python (by-value) converter found
for C++ type: std::vector<float, std::allocator<float> >, because Python needs to know how to
deal with std::vector.
std::vector<float> secondMethod() {
return std::vector<float>();
}
BOOST_PYTHON_MODULE(CppProject) {
// wrapper function
class_<std::vector<float> >("FloatVec")
.def(vector_indexing_suite<std::vector<float> >());
boost::python::def("getEmptyVec", secondMethod);
}
The result can be further converted into a Python list or Numpy array simply by calling list() and
numpy.asarray().
https://riptutorial.com/ 22
Credits
S.
Chapters Contributors
No
Async
2 Michaël Roy
boost::process
Boost Accumulators
3 Philipp Claßen
Framework
BOOST- Compare
4 Images using DivyaMaheswaran
OpevCV
Boost Program
5 paul-g
Options
boost String
6 Zopesconk
Algorithms Library
https://riptutorial.com/ 23