UPI Study › Courses › C++ Programming › Free lessons › Lesson 8.2 Free with a free account
The C++ Standard Library
C++ Programming · Chapter 8: FunctionsSection 8.2 · lesson 52 of 84video coming soon
← Dividing Programs Into Callable UnitsNext lesson: Lifetime and Reach →
In this lesson
Tapping into ready-made functionality.
- Give real reasons to prefer a library function
- Read a signature in reference documentation
- Use <cmath>, and tell the rounding functions apart
- Seed random numbers; apply <algorithm> and <numeric>
Transcript
Everything said in the video, section by section (1,370 words). Read along, or search it.
Opening Idea
Why Reach for the Library First
Writing your own functions is the subject of this chapter. Knowing which ones not to write is just as much a skill. A great deal of what a program needs has already been written, specified by a standards committee, implemented by compiler vendors, and tested by millions of users for decades. Reaching for it first isn't laziness. It's usually the only way to get the edge cases right.
Worked Example
Hand-Rolled Rounding Fails on Negatives
Suppose you need to round a value to the nearest whole number. The obvious approach is to add a half, and discard the fraction. It's a one-liner any programmer would write without hesitation, and it's correct for every positive value you're likely to test. The last column is that hand-rolled version, and it's wrong for every negative value in the output. Minus 2.6 should round to minus 3, and becomes minus 2. Minus 2.4 should become minus 2, and becomes minus 1. The fault isn't carelessness. The reasoning is sound for positives, and simply doesn't carry over. It would pass a test suite built from positive data, and fail in production the first time an amount went negative.
The Argument
Why Library Functions Beat Your Own
That's the argument in miniature, and it generalizes. Edge cases have already been found. Negative values, zero, enormous values, values that can't be represented exactly: every one has been reported by somebody, years ago. Library functions are specified, not merely written. An international standard states what each must do, so the behavior is the same on every compiler and platform. They're usually faster, because implementations may use processor instructions built for the job. And they say what you mean. Sort tells a reader exactly what's happening; 20 lines implementing a sort tell them only after they've read all 20. So the rule is: if the standard library does it, use the standard library. The exception is when you're deliberately learning how something works. Writing your own sort once is valuable. Shipping it isn't.
Reading Signatures
Return Type, Name, and Parameter Order
Every library function is described by its signature: one line stating what it gives back, what it's called, and what it must be given. Pow returns a double: a fractional value, so even a whole-number answer arrives as one. It's called pow, written with the std prefix. And it takes two values, base and exponent, in that order. The names are documentation only. You pass your own values, but the order isn't optional. Documentation often lists several signatures for one name. That means the function accepts more than one combination of types, and the compiler picks the match. Beyond the signature, a reference page tells you two things you can't deduce: which header to include, and what happens at the boundaries. Those notes are the reason to read the page, rather than guess from the name.
Headers
C Names, C++ Forms, and std Prefix
Nothing in the library is available until the header supplying it is included. C++ inherited a large part of its library from C. Those parts appear under two spellings: the original C name, such as math dot h, and a C++ form, with the dot h dropped and a c prefixed, such as cmath. They supply the same functions. The C++ form places the names inside the std namespace, where the rest of the library lives. Cmath supplies mathematical functions. Cstdlib supplies general utilities, including rand and srand. Ctime supplies the time. Algorithm supplies sorting, searching and counting, and numeric supplies summing. So prefer the c-prefixed form, and write std colon colon. Bare names often work, because implementations commonly declare them in both places, but relying on that is relying on an accident.
Math Functions
Rounding Directions and Radian Trigonometry
Here are the most-used mathematical functions. Pow raises a base to a power, and the exponent needn't be whole: pow of 9 with an exponent of a half gives 3. Square root is preferred over pow of a half: it's clearer, and usually faster. Fabs gives the magnitude of a fractional value, with the sign discarded. Floor and trunc agree on positive values, and disagree on negative ones. Floor of minus 2.5 is minus 3. Trunc of minus 2.5 is minus 2. Picture a number line. Ceil always goes up the line. Floor always goes down it. Trunc always goes toward zero. And round goes to whichever whole value is nearer, with halves moving away from zero. The trigonometric functions take radians. Passing 30 to sine computes the sine of 30 radians, minus 0.988: a completely different, and perfectly valid, answer. Convert first, by multiplying the degrees by pi, and dividing by 180. Nothing warns you, because both calls are legal. It's a wrong answer, not a wrong program.
Random Numbers
Turning rand into a Die Roll
Std rand returns a whole number between zero and a maximum the implementation defines. Two adjustments turn that into something useful. The remainder of dividing by 6 narrows it to 0 through 5. Adding 1 shifts it to 1 through 6: a die roll. In general, for a value from low to high inclusive, take rand mod high minus low plus one, and add low. But rand doesn't produce randomness. It produces a fixed sequence, computed from a starting value called the seed. Unless you set that seed, it's the same every time. Run it twice: identical rolls, again and again.
Seeding
Seeding Once and Three Common Mistakes
Srand sets the seed. What's needed is a value that differs between runs, and the usual source is the clock. Seeded once at the start from the time, the program gives different rolls on each run. Here are two runs, a couple of seconds apart. Three things people get wrong. First, seeding inside the loop. Srand belongs once, at the start. Called before every draw, it reseeds from a clock that's barely moved, and the same value comes back. Second, assuming a fixed seed is a bug. It's sometimes exactly what you want: a constant seed reproduces the same sequence every run, which is invaluable when testing. Third, assuming mod n is evenly distributed. Unless the range divides the maximum exactly, the lowest values come up slightly more often. Fine for dice. For anything where fairness is the point, C++ has a dedicated random-number library.
Algorithms
Working Over Ranges with Begin and End
The algorithm and numeric headers supply operations that work over a run of values. Each is told where the data begins and where it ends, rather than being handed the collection itself. That's what lets one implementation of sorting serve arrays and every other collection alike. For an array, those two positions come from begin and end. And end means the position just after the final element, not the final element itself. Same convention as the loop condition i less than length. For these eight marks, the sum is 623, the highest 91, the lowest 54, and 91 appears twice. The average is 77.875, 65 is present, and sorted, they run 54 up to 91.
Return Values
What Each Algorithm Hands Back
Here's what each operation hands back. Accumulate returns the total. Its third argument is the value the total starts from. Max element and min element return the position of the largest or smallest value, not the value itself. Write a star before the call to read what's there. Count returns how many elements equal a value. Find returns the position of the first match, or the end position if there's none. Sort and reverse return nothing: they rearrange the data in place. One pattern is worth memorizing: not found is the end marker, just as a string search returns npos. Test for it explicitly.
Quick Check
Why Accumulate Printed 26
Quick check. This program sums the same three prices twice: once from a starting value of 0, and once from 0.0. What does each sum print? Pause and think. The first prints 26. Its starting value, 0, is an int, so every addition was done in whole numbers, and each fraction was thrown away along the way. The second starts from 0.0, a double, and prints the true total, 27.74. The starting value sets the type of the arithmetic, so pass 0.0.
Key Takeaways
Library First, Read Docs, Seed Once
To summarize. Prefer the library. It's tested, specified, usually faster, and it says what you mean. Read a function's signature, then the reference page's notes on headers and edge cases. Include cmath and write std. Trigonometry takes radians. Seed random numbers once, and use a fixed seed for testing. And ranges end one past the last element, which is also how a search reports not found.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About The C++ Standard Library
Why should I use a C++ library function instead of writing my own?
What is the difference between floor, ceil, trunc, and round in C++?
How do I seed rand and simulate a die roll in C++?
Why does std::accumulate drop the decimals when I sum doubles?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →