B. Stroustrup - The C++ Programming Language (794319), страница 34
Текст из файла (страница 34)
For example:void f(complex<float> fl, complex<double> db){complex<long double> ld {fl+sqrt(db)};db += fl∗3;fl = pow(1/fl,2);// ...}The sqrt() and pow() (exponentiation) functions are among the usual mathematical functions definedin <complex>. For more details, see §40.4.5.6.3 Random NumbersRandom numbers are useful in many contexts, such as testing, games, simulation, and security.The diversity of application areas is reflected in the wide selection of random number generatorsprovided by the standard library in <random>. A random number generator consists of two parts:[1] an engine that produces a sequence of random or pseudo-random values.[2] a distribution that maps those values into a mathematical distribution in a range.Examples of distributions are uniform_int_distribution (where all integers produced are equallylikely), normal_distribution (‘‘the bell curve’’), and exponential_distribution (exponential growth);each for some specified range.
For example:using my_engine = default_random_engine;using my_distribution = uniform_int_distribution<>;// type of engine// type of distributionmy_engine re {};my_distribution one_to_six {1,6};auto die = bind(one_to_six,re);// the default engine// distribution that maps to the ints 1..6// make a generatorint x = die();// roll the die: x becomes a value in [1:6]The standard-library function bind() makes a function object that will invoke its first argument(here, one_to_six) given its second argument (here, re) as its argument (§33.5.1). Thus a call die() isequivalent to a call one_to_six(re).130A Tour of C++: Concurrency and UtilitiesChapter 5Thanks to its uncompromising attention to generality and performance one expert has deemed thestandard-library random number component ‘‘what every random number library wants to be whenit grows up.’’ However, it can hardly be deemed ‘‘novice friendly.’’ The using statements makeswhat is being done a bit more obvious.
Instead, I could just have written:auto die = bind(uniform_int_distribution<>{1,6}, default_random_engine{});Which version is the more readable depends entirely on the context and the reader.For novices (of any background) the fully general interface to the random number library can bea serious obstacle. A simple uniform random number generator is often sufficient to get started.For example:Rand_int rnd {1,10};int x = rnd();// make a random number generator for [1:10]// x is a number in [1:10]So, how could we get that? We have to get something like die() inside a class Rand_int:class Rand_int {public:Rand_int(int low, int high) :dist{low,high} { }int operator()() { return dist(re); }// draw an intprivate:default_random_engine re;uniform_int_distribution<> dist;};That definition is still ‘‘expert level,’’ but the use of Rand_int() is manageable in the first week of aC++ course for novices.
For example:int main(){Rand_int rnd {0,4};// make a uniform random number generatorvector<int> histogram(5);for (int i=0; i!=200; ++i)++histogram[rnd()];// make a vector of size 5// fill histogram with the frequencies of numbers [0:4]for (int i = 0; i!=mn.size(); ++i) {// write out a bar graphcout << i << '\t';for (int j=0; j!=mn[i]; ++j) cout << '∗';cout << endl;}}The output is a (reassuringly boring) uniform distribution (with reasonable statistical variation):01234∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗Section 5.6.3Random Numbers131There is no standard graphics library for C++, so I use ‘‘ASCII graphics.’’ Obviously, there are lotsof open source and commercial graphics and GUI libraries for C++, but in this book I’ll restrictmyself to ISO standard facilities.For more information about random numbers, see §40.7.5.6.4 Vector ArithmeticThe vector described in §4.4.1 was designed to be a general mechanism for holding values, to beflexible, and to fit into the architecture of containers, iterators, and algorithms.
However, it does notsupport mathematical vector operations. Adding such operations to vector would be easy, but itsgenerality and flexibility precludes optimizations that are often considered essential for seriousnumerical work. Consequently, the standard library provides (in <valarray>) a vector-like template,called valarray, that is less general and more amenable to optimization for numerical computation:template<typename T>class valarray {// ...};The usual arithmetic operations and the most common mathematical functions are supported forvalarrays.
For example:void f(valarray<double>& a1, valarray<double>& a2){valarray<double> a = a1∗3.14+a2/a1;// numeric array operators *, +, /, and =a2 += a1∗3.14;a = abs(a);double d = a2[7];// ...}For more details, see §40.5. In particular,mensional computations.valarrayoffers stride access to help implement multidi-5.6.5 Numeric LimitsIn <limits>, the standard library provides classes that describe the properties of built-in types – suchas the maximum exponent of a float or the number of bytes in an int; see §40.2.
For example, wecan assert that a char is signed:static_assert(numeric_limits<char>::is_signed,"unsigned characters!");static_assert(100000<numeric_limits<int>::max(),"small ints!");Note that the second assert (only) works because(§2.2.3, §10.4).numeric_limits<int>::max()is aconstexprfunction132A Tour of C++: Concurrency and UtilitiesChapter 55.7 Advice[1][2][3][4][5][6][7][8][9][10][11][12][13]Use resource handles to manage resources (RAII); §5.2.Use unique_ptr to refer to objects of polymorphic type; §5.2.1.Use shared_ptr to refer to shared objects; §5.2.1.Use type-safe mechanisms for concurrency; §5.3.Minimize the use of shared data; §5.3.4.Don’t choose shared data for communication because of ‘‘efficiency’’ without thought andpreferably not without measurement; §5.3.4.Think in terms of concurrent tasks, rather than threads; §5.3.5.A library doesn’t have to be large or complicated to be useful; §5.4.Time your programs before making claims about efficiency; §5.4.1.You can write code to explicitly depend on properties of types; §5.4.2.Use regular expressions for simple pattern matching; §5.5.Don’t try to do serious numeric computation using only the language; use libraries; §5.6.Properties of numeric types are accessible through numeric_limits; §5.6.5.Part IIBasic FacilitiesThis part describes C++’s built-in types and the basic facilities for constructing programs out of them.
The C subset of C++ is presented together with C++’s additionalsupport for traditional styles of programming. It also discusses the basic facilities forcomposing a C++ program out of logical and physical parts.Chapters6789101112131415Types and DeclarationsPointers, Arrays, and ReferencesStructures, Unions, and EnumerationsStatementsExpressionsSelect OperationsFunctionsException HandlingNamespacesSource Files and Programs134Basic FacilitiesPart II‘‘...
I have long entertained a suspicion, with regard to the decisions of philosophersupon all subjects, and found in myself a greater inclination to dispute, than assent totheir conclusions. There is one mistake, to which they seem liable, almost withoutexception; they confine too much their principles, and make no account of that vastvariety, which nature has so much affected in all her operations. When a philosopherhas once laid hold of a favourite principle, which perhaps accounts for many naturaleffects, he extends the same principle over the whole creation, and reduces to it everyphænomenon, though by the most violent and absurd reasoning.
...’’– David Hume,Essays, Moral, Political, and Literary. PART I. (1752)6Types and DeclarationsPerfection is achievedonly on the point of collapse.– C. N. Parkinson••••••The ISO C++ StandardImplementations; The Basic Source Character SetTypesFundamental Types; Booleans; Character Types; Integer Types; Floating-Point Types; Prefixes and Suffixes; void; Sizes; AlignmentDeclarationsThe Structure of Declarations; Declaring Multiple Names; Names; Scope; Initialization;Deducing a Type: auto and decltype()Objects and ValuesLvalues and Rvalues; Lifetimes of ObjectsType AliasesAdvice6.1 The ISO C++ StandardThe C++ language and standard library are defined by their ISO standard: ISO/IEC 14882:2011.