Step into Boost

There has always been a saying that if you want to become a master, you must read more source code written by masters. What codes are good material? Source code for the C++ Standard Library? No, if you read it, you’ll find that either the implementation-specific expressions are confusing, or the horrible code style (like underlining everywhere) is uncomfortable. The code of the Boost library is quite clear, well-commented, and well-named, which is definitely a good example for reading. At the same time, Boost has a wide range of content, numerical computing, generic programming, meta-programming, platform APIs… Choose the part that interests you and savor it.

In this article, we will introduce the download and installation of the Boost library, and will experience a very simple and practical component of the Boost library:lexcial_cast

Introduction to Boost

What is Boost? An open source, highly portable set of C++ libraries.
Who initiated it? C++ Standards Committee Library Working Group. Therefore, quality assurance, not afraid of encountering counterfeit and shoddy products.

What’s the matter? And voila:

  • regular expressions, which are comparable to the POSIX API and Perl language’s ability to handle regular expressions, and can also support a variety of character types (such as char, wchar_t, and even custom character types);
  • Multithreading, a cross-platform multithreaded library that I have been thinking about for a long time;
  • Data structure “graph”, coupled with the upcoming 、、、 to the standard (in fact, many STL implementations, such as SGI STL, already support the above data structures), C++’s support for data structures is almost complete;hash_sethash_maphash_multisethash_multimap
  • python, that’s right, support for the Python language;
  • Smart pointers, when used together, can eliminate memory leakage, and the efficiency cannot be the same as the garbage collection mechanism GC;std::auto_ptr
  • More cyclic redundancy CRC, easy definition of tuples that return multiple value functions, accommodation of different types of values, complementing all aspects of the standard library…tupleany
  • It’s still expanding rapidly, and some of the content is expected to enter the C++ standard library…

Download and install

Where can I download Boost? English [1], Chinese, a compressed package in .zip or .tar.gz format can be found. After downloading, extract it to a directory, such as boost_1_26_0, which generally has several subdirectories: boost, libs, more, people, status, tools, and see if there is no problem.

If you are too lazy to download the entire archive when Boost is updated, you only want to update the changed files; Or if you’re a Boost fan like me and want to keep track of the latest changes to Boost, you might as well use CVS. The first thing is to have a CVS client software, such as WinCVS, gCVS, and MacCVS from CvsGui ( or, which are available for Windows, Linux, and MacOS platforms respectively. Download, install, and launch in three steps.

If you are used to the command line mode of traditional CVS, you can → Command Line in Admin… Enter the following line [2] → Command line settings:
cvs -z3 -d:pserver:a[email protected]:/cvsroot/boost checkout boost
Tick the checkbox below, select the local destination directory (for example, you can create a new C:\Boost, which depends on personal preference), and click OK to start the update. If it’s the first run, it may take a while to download all the files. Of course, it will only take a short time to update later.

If you prefer GUI mode, select Admin→Preferences…, and enter
[email protected]:/cvsroot/boost
in General’s Enter CVS ROOT Authentication selects “passwd” file on the cvs server, and cvs 1.10 (standard) is selected for Use version. Then fill in or select a local destination directory in the HOME folder of WinCvs and click OK. Select View→Browse Location→Change… After switching to the local target directory, in the Create→Check Module… Enter the module name and path on the server in → Checkout Settings and click OK. If you are asked to enter a password during this process, don’t bother and just enter it. This is the case with WinCVS 1.2. If you download a new version, please note that the settings are similar, such as the previous Authentication selection pserver, do not need to set Use version, etc.

Then set up the compiler. Take the Windows common integration environment as an example. Microsoft Visual C++ 6.0, you can add the path to Boost (as in the previous boost_1_26_0) to the Include Files search path by selecting the → directory in the Tools →. For Borland C++ Builder 5.0, the path to Boost is added to Project→Options→Directories/Conditionals→Include Path. There is also a more commonly used Dev-C++ 4.0 (built-in GNU C++, available from http://www.bloodshed.netYou can add the path to Boost at Options→Compile Options→Directories→C++ include files. Other IDEs are similar. As for the command line mode, you need to give the Boost path to the corresponding header file path parameter (Borland C++ Compiler, GNU C++ is -I, VC++ cl is /I) at compile time.

This step, congratulations, most of the Boost library is ready to use.

Why not all? First of all, there is currently no compiler that fully complies with the C++ standard, so the components in the Boost library are more or less unavailable, see the “Compiler Status” article on the Boost website for details. In addition, some libraries require a corresponding lib or dll file to be built. However, there are few such libraries, mainly due to platform dependencies, such as the regex library that handles regular expressions, the python library that supports the python language, etc., and the process of constructing the library is quite cumbersome and requires the use of Jam tools (it can be briefly mentioned: there are three files in the tools/build/jam_src/builds directory,, are the Mark files for Borland C++ Compiler, GNU C++, and Visual C++ for Windows. If you are on a Unix platform, you should use tools/build/Makefile. Use the command line tool make or nmake to make the Jam executable file, and then use the Jam to build the library, see the Boost.Build documentation for details). My personal advice is not to rush to build lib or dll. When you really need to use these libraries, just make the mak files provided with the library. Although Boost.Jam may be the future development direction of the Boost library, after all, most libraries do not need to be built and can be used directly.


This time, let’s pick a simple and practical Boost component to see what convenience Boost can bring us.

String→ numeric value

CSDN forums often see questions asking how to convert between string types and numeric types, and many different answers. Let’s start with the conversion from string to numeric types.

How do I convert string “123” to an integer of type int type 123? The answer is, with the library functions of standard C;
What if you want to convert to the long type? Standard C’s library functions;
How do I convert “123.12” to double? Standard C’s library functions;
What if you want to convert to the long double type? Standard C’s library functions;
…… atoiatolatodatold

Later, a friend began to use the standard library and asked how to convert this to a numeric value? A friend replied, please convert to const char* first. I admire the respondent’s mathematician thinking: transforming unfamiliar problems into familiar ones. (There was once a joke where a good deed asked a mathematician: Do you know how to boil water?) A: Yes. Fill the kettle with water and set it on fire. And asked: What if there is already water in the kettle? A: Dump it first, and it will turn into a familiar problem… ) string类

No, no, that’s the C approach, not C++. So, what to do with C++? Using the functions provided by the Boost Conversion Library (which requires the introduction of the header file boost/lexical_cast.hpp) is undoubtedly the easiest and most convenient. As: lexical_cast

#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
	using boost::lexical_cast;
	int a = lexical_cast<int>("123");
	double b = lexical_cast<double>("123.12");
	return 0;

One function succinctly solves all problems.

Numeric → string

And what about going from numeric type to string type?

Use? No, there is no such function in standard C/C++. Even if some compilers provide this function [3] under the Windows platform, there is no portability, and it can only solve int types (maybe other functions can also solve long, unsigned long and other types), what about floating-point types? Of course, there is still a way, that is: itoasprintf

char s[100];
sprintf(s, "%f", 123.123456);

I don’t know what your impression of the series in C is, in short, I definitely can’t remember those strange parameters, and if you write the wrong parameters, you will get inexplicable output results, and debugging is fatal (I hate the character array more, the space is 100, and I’m afraid it’s too small to fit; Open 100000, I always feel too wasteful, and I hold my breath, but fortunately, the C++ standard provides us with such a string class). At this time, come out to help. It’s as simple as before. scanf/printfstringlexical_cast

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
int main()
	using std::string;
	const double d = 123.12;
	string s = boost::lexical_cast<string>(d);
	return 0;



If the conversion fails, an exception is thrown. The exception class is a subclass of the standard exception class. bad_lexical_castbad_cast

#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
	using std::cout;
	using std::endl;
	int i;
		i = boost::lexical_cast<int>("abcd");
	catch(boost::bad_lexical_cast& e)
		return 1;
	return 0;

Obviously, “abcd” cannot be converted to an int value, so an exception is thrown and the message “bad lexical cast: source type value could not be interpreted as target” is output after capture.


lexical_castRelying on character streams (which automatically introduce headers<sstream>[4]), the principle is fairly simple: read the source type into the character stream, write it to the target type, and you’re done. For example std::stringstream

int d = boost::lexical_cast<int>("123");

It is equivalent to Since character flow is used, of course, there are some problems that come with it, which need to be pointed out in particular [5].

int d;
std::stringstream s;
  1. Due to the problematic implementation of the locale part of Visual C++ 6, exceptions may be thrown inexplicably if a non-default locale is used. Of course, in general, we don’t need to change the default locale, so the problem is not very big.
  2. The input data must be converted “completely” or an exception is thrown. For examplebad_lexical_cast
        int i = boost::lexical_cast<int>("123.123"); // this will throw

    An exception is thrown. Because “123.123” can only be converted to 123 “partially”, not “completely” to 123.123.

  3. Precision issues with floating-point numbers.
     std::string s = boost::lexical_cast<std::string>(123.1234567);

    The expected result of the above statement is “123.1234567”, but in reality we will only get “123.123”, because the precision by default is 6 (this is the tradition left by the “predecessors” in the C library). This can be said to be a bug. What to do about it? As a workaround, you can do this: open the header file <boost/lexical_cast.hpp> and pay attention to the [6]: to get the correct result. Of course, there is a slight loss of efficiency in theory, but it is almost negligible.std::stringstreamprintfboost::lexical_cast

    #include <boost/limits.hpp>
    template<typename Target, typename Source>
    Target lexical_cast(Source arg) {
         Target result; 
         if( !(interpreter << arg) ||
         !(interpreter >> result) ||
         !(interpreter >> std::ws).eof())


Brief summary

We have already experienced it. Of course, this is not limited to converting between string types and numeric types: you can convert between any type that can be output to and any type that can be imported from. Although this understanding is very rough, after all, we have “walked into Boost”, not just “approached”. Later, we can see the excitement of Boost on our own. boost::lexcial_castlexical_caststringstreamstringstream

[1] If you get a DNS error when visiting the Boost website, try

[2] Please refer to the “Boost Download and Installation” section of the Boost documentation.

[3] Borland C++ Builder provides, while Microsoft Visual C++ provides a function that functions the same, but with the name.itoa_itoa

[4] In some non-standard standard library implementations, the character stream class name is, in the header file <strstream >. The standard specifies that in header files < sstream >.strstreamstringstream

[5] Please refer to the discussion in

[6] Many thanks to Andrew Koenig and Bjarne Stroustrup for their advice and help. At first, my idea was to specify maximum precision and add statements like that, but I was worried about portability. Mr. Andrew Koenig gave a very clear explanation: You are quite correct that 15 is not portable across all floating-point implementations. However, it is portable across all implementations that support IEEE floating-point arithmetic, which is most computers that are in common use today. If you want to do better than that, you might consider using , which is the number of significant base-10 digits that can be accurately represented in a double. (Chinese to the effect that, admittedly, 15 is not portable to all floating-point implementations, but it is indeed portable for implementations that support IEEE floating-point arithmetic, and this is what most computers use today. If you want to do a little better, you can consider using it, which can express the number of digits that double can express accurately in decimal. ) interpreter.precision(15)numeric_limits<double>::digits10numeric_limits<double>::digits10

Related Articles

Dev-C++ Resource

Feature list Support GCC-based compilers Integrated debugging (using GDB) Class Browser (experimental) Code Completion (experimental) Project Manager Customizable syntax highlighting editor Quickly create Windows, console, static libraries and DLLs Support of templates for creating your own project types Makefile creation Edit and compile Resource files Tool Manager Print support Find and

Read More »