Address: http://dozb.bokee.com/1871748.html
There is always a saying that to become a master, you must read more highly handwrittenSource code. WhichCodeWhat about good materials? C ++ standard library source code? No, if you have read it, you will find that either a variety of expressions that are unique to implementation are confusing, or a horrible code style (such as an underline everywhere) is uncomfortable. The boost library code is quite clear, reasonable comments, and naming conventions are definitely a good example for reading. At the same time, boost has a wide range of content, such as numerical computing, generic programming, metaprogramming, and platform API ...... You may wish to carefully select what you are interested in.
In this article, we will introduce the download and installation of the boost library, and will experience a very simple and practical component in the boost library.Lexcial_cast.
Directory
-
Boost Introduction
-
Download and install
-
Lexical_cast
-
-
String → Value
-
Value → string
-
Exception
-
Notes
-
Summary
Boost Introduction
What is boost? A set of open source code and highly portable C ++ libraries.
Who initiated it? C ++ Standards Committee Database Working Group. Therefore, quality assurance is not afraid of counterfeit and shoddy products.
What about it? Look:
- regular expressions can be used to process regular expressions in posix api and Perl, and support various character types (such as char, wchar_t, it can even be a custom character type);
- multithreading: I have been thinking about a cross-platform multi-threaded library for a long time.
- Data Structure "Graph", plus the
hash_set , hash_map , hash_multiset , hash_multimap (in fact, many STL implementations, such as sgi stl, support the above data structures ), c ++'s support for data structures is nearly complete.
- Python: Yes. Support for python
- smart pointer, with
STD :: auto_ptr can be used together to prevent memory leaks and make it more efficient than GC.
- more cyclic redundancy CRC, and the ability to easily define the tuples that return multiple value functions
tuple : Any . supplement the standard library ......
- some content is expected to enter the C ++ standard library ......
Download and install
Where can I download boost? English http://www.boost.org [1], Chinese http://boost.c-view.org, can find a. zipor .tar.gz format compressed package. After the download is complete, decompress the package to a directory, such as boost_000026_0, which generally contains the following subdirectories: boost, Libs, more, people, status, and tools. Just check if there is no problem.
If you are too reluctant to download the entire package when the boost is updated, you only want to update the file that has changed; or you are a boost fans like me, and want to track the latest boost changes, use CVs. First, you have to have a CVS client software, such as the wincvs, gcvs, and maccvs provided by cvsgui (http://www.wincvs.org or http://sourceforge.net/projects/cvsgui/), for Windows, Linux, and MACOs platforms, respectively. Download, install, and start.
if you are used to the command line mode of traditional CVs, you can choose admin> command line... → enter the following line in command line settings [2]:
CVS-Z3-D: pserver: anonymous@cvs.boost.sourceforge.net: /cvsroot/Boost checkout boost
check the following check box and select the local target directory (for example, you can create a new c: \ boost, which depends on your personal interests ), click OK to start the update. If this is the first time, it may take some time to download all the files. Of course it will take a short time to update later.
If you prefer the GUI mode, select Admin> preferences ..., enter:
anonymous@cvs.boost.sourceforge.net:/cvsroot/Boost
authentication in general's enter CVS root select "passwd" file on the CVS server, select CVS 1.10 (standard) for use version ). In wincvs's home folder, enter or select a local target directory and click OK. Select view → browse location → change... after changing to the local target directory, go to create → check module... → enter the module name and path in the server of the checkout settings, enter boost, and click OK. If you need to enter the password during this process, just press Enter. This is where wincvs 1.2 is used. If you are downloading a new version, pay attention to the same settings. For example, if you select pserver for the previous authentication, you do not need to set use version.
Then set the compiler. Take windows integrated environment as an example. Microsoft Visual C ++ 6.0, you can add the boost path (for example, boost_000026_0 in front of the tool → select → directory) to the include files search path. For Borland C ++ Builder 5.0, the boost path is added to project → options → directories/conditionals → include path. There is also a more common Dev-C ++ 4.0 (built-in gnu c ++, which can be downloaded free of charge from the http://www.bloodshed.net ), you can add the boost path in Options → compile options → directories → C ++ include files. Similar to other ides. For the command line method, you need to specify the path parameters for the corresponding header file during compilation (Borland C ++ compiler, gnu c ++ is-I, and VC ++'s Cl Is/I) the boost path is provided.
Congratulations, you can use most of the boost libraries.
Why not all? First of all, there is no compiler that fully complies with the c ++ standard, so the components in the boost library are more or less unavailable. For details, see "compiler support (compiler status)" on the boost website). In addition, some libraries need to build corresponding lib or DLL files. However, there are few such libraries, mainly because of platform relevance, such as the RegEx library for processing Regular Expressions and Python library that supports the Python language. The process of constructing a library is cumbersome, you need to use the jam tool (you can simply mention: In the tools/build/jam_src/builds directory there are three file win32-borlandc.mk, win32-gcc.mk, win32-visualc.mk, these are Mak files for Borland C ++ compiler, gnu c ++, and Visual C ++ on 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 execution file, and then use jam to construct the library. For details, see the boost. Build document ). My personal suggestion is that you do not need to rush to construct lib or DLL. Make the Mak file provided with the library when you really need to use these libraries. Although boost. Jam may be the future direction of boost libraries, most libraries do not need to be constructed and can be used directly.
Lexical_cast
This time, we will first pick a simple and practical boost component to see how convenient boost can bring us.
String → Value
On the csdn forum, I often see questions about how to convert string and numeric types. I also see many different answers. Next we will first discuss the conversion from the string type to the numeric type.
How to convert a string "123" to an integer of the int type 123? The answer is: Use Standard C library functions.Atoi;
What if you want to convert it to the long type? Library functions of Standard CAtol;
How to convert "123.12" to double type? Library functions of Standard CAtod;
What if I want to convert it to the long double type? Library functions of Standard CAtold;
......
Later, a friend started to useString typeAnd how to convert it to a value? A friend replied, Please convert it to const char * first *. I admire the mathematician's thinking of the Q & A: Turning unfamiliar questions into familiar questions. (Once there was a joke, so I asked mathematicians: Do you know how to boil water? A: Yes. Fill the water bottle with water and ignition. Q: What if there is already water in the kettle? A: Switch it down first and it turns into a problem that I am familiar ......)
No, no. This is the practice of C, not c ++. So what should C ++ do? Functions provided by boost conversion LibraryLexical_cast(The header file boost/lexical_cast.hpp needs to be introduced) is undoubtedly the simplest and most convenient. For example:
# 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"); STD: cout <A <STD: endlstd: cout <B <STD: Endl; return 0 ;}
A function solves all the problems in a simple way.
Value → string
So from the value type to the string type?
UseITOA? No, this function is not available in Standard C/C ++. Even if some compilers on Windows provide the function [3], the function can only be of the int type without any portability. (Other functions can also be of the long or unsigned long type ), what about the floating point type? Of course, there are still some solutions, that is:Sprintf.
Char s [100]; sprintf (S, "% F", 123.123456 );
I don't know whatScanf/PrintfWhat are the series impressions? In a word, I certainly cannot remember the odd parameters. If a parameter is wrong, I will get an inexplicable output result, debugging is terrible. (what I hate more is the character array, where the space is opened at 100. I am afraid that it is too small to fit. When I open the character array at 100000, I always feel that it is too wasteful and I feel so angry, fortunately, the C ++ standard provides usStringSuch a string class ). At this time,Lexical_castLet's help.
# 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); STD: cout <S <STD: Endl; return 0 ;}
It is as simple as above.
Exception
If the conversion fails, an exception occurs.Bad_lexical_castThrow. This exception class is a standard exception class.Bad_cast.
# Include <boost/lexical_cast.hpp> # include <iostream> int main () {Using STD: cout; Using STD: Endl; int I; try {I = boost :: lexical_cast <int> ("ABCD");} catch (boost: bad_lexical_cast & E) {cout <E. what () <Endl; return 1 ;}cout <I <Endl; return 0 ;}
Obviously, "ABCD" cannot be converted to an int value. Therefore, an exception is thrown, and information such as "bad lexical cast: Source Type value cocould not be interpreted as target" is output.
Notes
Lexical_castDependent on Ghost streamSTD: stringstream(The header file <sstream> [4] is automatically introduced.) The principle is quite simple: Read the source type into the intent stream and write it to the target type. For example
Int d = boost: lexical_cast <int> ("123 ");
It is equivalent
Int D; STD: stringstream s; S <"123"; S> D;
Since the ghost stream is used, of course there are some problems that come with it, which need to be pointed out in particular [5].
-
Due to some problems with the locale implementation of visual c ++ 6, if non-default locale is used, an exception may be thrown inexplicably. Of course, in general, we do not need to change the default locale, so the problem is not great.
The input data must be completely converted; otherwiseBad_lexical_castException. For example
Int I = boost: lexical_cast <int> ("123.123"); // This will throw
An exception is thrown. Because "123.123" can only be partially converted to 123, and cannot be fully converted to 123.123.
The accuracy of floating point numbers.
STD: String S = boost: lexical_cast <STD: String> (123.1234567 );
The expected result of the preceding statement is "123.1234567", but we only get "123.123" becauseSTD: stringstreamThe precision is 6 (this is the C LanguageProgram"Predecessors" in the library"PrintfLegacy ). This can be said to beBoost: lexical_cast. What should we do? You can do this by opening the header file <boost/lexical_cast.hpp>. Note that you can modify the header file [6]:
# Include <boost/limits. HPP> //... template <typename target, typename source> Target lexical_cast (source Arg ){//... target result; interpreter. precision (STD: numeric_limits <source>: digits10); If (! (Interpreter <Arg) |! (Interpreter> result) |! (Interpreter> STD: WS). EOF ())//...}
You can get the correct result. Of course, theoretically, the efficiency will suffer a little loss, but it is almost negligible.
Summary
We have already experiencedBoost: lexcial_cast. Of course,Lexical_castIt is not limited to conversions between string and numeric types: It can be outputStringstreamAnd anyStringstreamConverts input types. Although this understanding is rough, after all, we have "walked into boost", not just "approaching ". In the future, we will be able to appreciate the benefits of boost.
[1] If a DNS error occurs when you access the boost English website, try http: // 64.226.201.52 /.
[2] See "Boost download and installation" in the boost documentation.
[3] Borland C ++ Builder providesITOAMicrosoft Visual C ++ provides a function with the same functions, but its name is_ ITOA.
[4] In some standard library implementations that do not comply with the standards, the streaming class name isStrstreamIn the header file <strstream>. The standard stipulates thatStringstreamIn the header file <sstream>.
[5] For more information, see the discussion at http://groups.yahoo.com/group/boost/message/15023.
[6] I am very grateful to Andrew Koenig and Bjarne stroustrup for their suggestions and help. At first, my idea was to specify the maximum precision and add Interpreter. Precision (15) Such statements, but worry about portability. Mr. Andrew Koenig gave a very clear explanation: You are quite correct that 15 is not portable internal SS all floating-point implementations. however, it is portable within SS 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 Numeric_limits <double >:: digits10 , Which is the number of significant base-10 digits that can be accurately represented in a double. (It is true that 15 is not portable to all floating-point implementations, but it is indeed portable for implementations that support IEEE floating-point operations, this is also used by most computers today. If you want to do better, you can consider using Numeric_limits <double >:: digits10 To indicate the number of digits that can be accurately expressed in the decimal double .)
End