




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Contents
Chapter 0 Getting started 0.1 Comments 0.2 #include 0.3 The main function 0.4 Curly braces 0.5 Using the standard library for output 0.6 The return statement 0.7 A slightly deeper look 0.8 Details Chapter 1 Working with strings 1.1 Input 1.2 Framing a name 1.3 Details Chapter 2 Looping and counting 2.1 The problem 2.2 Overall structure 2.3 Writing an unknown number of rows 2.4 Writing a row 2.5 The complete framing program 2.6 Counting 2.7 Details Chapter 3 Working with batches of data 3.1 Computing student grades 3.2 Using medians instead of averages 3.3 Details Chapter 4 Organizing programs and data 4.1 Organizing computations 4.2 Organizing data 4.3 Putting it all together 4.4 Partitioning the grading program 4.5 The revised grading program 4.6 Details Chapter 5 Using sequential containers and analyzing strings 5.1 Separating students into categories 5.2 Iterators 5.3 Using iterators instead of indices 5.4 Rethinking our data structure for better performance 5.5 The list type 5.6 Taking strings apart 5.7 Testing our split function 5.8 Putting strings together 5.9 Details Chapter 6 Using library algorithms 6.1 Analyzing strings 6.2 Comparing grading schemes 6.3 Classifying students, revisited 6.4 Algorithms, containers, and iterators 6.5 Details Chapter 7 Using associative containers 7.1 Containers that support efficient look-up 7.2 Counting words 7.3 Generating a cross-reference table 7.4 Generating sentences 7.5 A note on performance 7.6 Details Chapter 8 Writing generic functions 8.1 What is a generic function? 8.2 Data-structure independence 8.3 Input and output iterators 8.4 Using iterators for flexibility 8.5 Details Chapter 9 Defining new types 9.1 Student_info revisited 9.2 Class types 9.3 Protection 9.4 The Student_info class 9.5 Constructors 9.6 Using the Student_info class 9.7 Details Chapter 10 Managing memory and low-level data structures 10.1 Pointers and arrays 10.2 String literals revisited 10.3 Initializing arrays of character pointers 10.4 Arguments to main
The C++ In-Depth Series
Bjarne Stroustrup, Editor
"I have made this letter longer than usual, because I lack the time to make it short. " —Blaise Pascal
The advent of the ISO/ANSI C++ standard marked the beginning of a new era for C++ programmers. The standard offers many new facilities and opportunities, but how can a real-world programmer find the time to discover the key nuggets of wisdom within this mass of information? The C++ In-Depth Series minimizes learning time and confusion by giving programmers concise, focused guides to specific topics.
Each book in this series presents a single topic, at a technical level appropriate to that topic. The Series' practical approach is designed to lift professionals to their next level of programming skills. Written by experts in the field, these short, in-depth monographs can be read and referenced without the distraction of unrelated material. The books are cross-referenced within the Series, and also reference The C++ Programming Language by Bjarne Stroustrup.
As you develop your skills in C++, it becomes increasingly important to separate essential information from hype and glitz, and to find the in-depth content you need in order to grow. The C++ In-Depth Series provides the tools, concepts, techniques, and new approaches to C++ that will give you a critical edge.
Accelerated C++: Practical Programming by Example, Andrew Koenig and Barbara E. Moo Essential C++, Stanley B. Lippman Exceptional C++; 47 Engineering Puzzles, Programming Problems, and Solutions, Herb Sutter Modern C++ Design: Applied Generic Programming and Design Patterns, Andrei Alexandrescu
For more information, check out the series Web site at http://www.aw.com/cseng/series/indepth/
We assume that you want to learn quickly how to write useful C++ programs. Therefore, we start by explaining the most useful parts of C++. This strategy may seem obvious when we put it that way, but it has the radical implication that we do not begin by teaching C, even though C++ builds on C. Instead, we use high-level data structures from the start, explaining only later the foundations on which those data structures rest. This approach lets you to begin writing idiomatic C++ programs immediately.
Our approach is unusual in another way: We concentrate on solving problems, rather than on exploring language and library features. We explain the features, of course, but we do so in order to support the programs, rather than using the programs as an excuse to demonstrate the features.
Because this book teaches C++ programming, not just features/it is particularly useful for readers who already know some C++, and who want to use the language in a more natural, effective style. Too often, people new to C++ learn the language mechanics without learning how to apply the language to everyday problems.
We used to teach a week-long intensive C++ course every summer at Stanford University. We originally adopted a traditional approach to that course: Assuming that the students already knew C, we started by showing them how to define classes, and then moved systematically through the rest of the language. We found that our students would be confused and frustrated for about two days—until they had learned enough that they could start writing useful programs. Once they got to that point, they learned quickly.
When we got our hands on a C++ implementation that supported enough of what was then the brand-new standard library, we overhauled the course. The new course used the library right from the beginning, concentrated on writing useful programs, and went into details only after the students had learned enough to use those details productively.
The results were dramatic: After one day in the classroom, our students were able to write programs that had taken them most of the week in the old course. Moreover, their frustration vanished.
Our approach is possible only because C++, and our understanding of it, has had time to mature. That maturity has let us ignore many of the low-level ideas that were the mainstay of earlier C++ programs and programmers.
The ability to ignore details is characteristic of maturing technologies. For example, early automobiles broke down so often that every driver had to be an amateur mechanic. It would have been foolhardy to go for a drive without knowing how to get back home even if something went wrong. Today's drivers don't need detailed engineering knowledge in order to use a car for transportation. They may wish to learn the engineering details for other reasons, but that's another story entirely.
We define abstraction as selective ignorance—concentrating on the ideas that are relevant to the task at hand, and ignoring everything else—and we think that it is the most important idea in modern programming. The key to writing a successful program is knowing which parts of the problem to take into account, and which parts to ignore. Every programming language offers tools for creating useful abstractions, and every successful programmer knows how to use those tools.
We think, abstractions are so useful that we've filled this book with them. Of course, we don't usually call them abstractions directly, because they come in so many forms. Instead, we refer to functions, data structures, classes, and inheritance—all of which are abstractions. Not only do we refer to them, but we use them throughout the book.
approach.
Once you have understood how to use the library, you will be ready to learn about the low-level facilities on which the library is built, and how to use those facilities to write your own libraries. Moreover, you will have a feeling for how to make a library useful, and when to avoid writing new library code altogether.
Although this book is smaller than many C++ books, we have tried to use every important idea at least twice, and key ideas more than that. As a result, many parts of the book refer to other parts. These references look like §39.4.3/857, which refers to text on page 857 that is part of section 39.4.3—or at least it would do so if this book had that many sections or pages. The first time we explain each idea, we mention it in bold italic type to make it easy to find and to call your attention to it as an important point.
Every chapter (except the last) concludes with a section called Details. These sections serve two purposes: They make it easy to remember the ideas that the chapter introduced, and they cover additional, related material that we think you will need to know eventually. We suggest that you skim these sections on first reading, and refer back to them later as needed.
The two appendices summarize and elucidate the important parts of the language and library at a level of detail that we hope will be useful when you are writing programs.
Getting the most out of this book
Every book about programming includes example programs, and this one is no different. In order to understand how these programs work, there is no substitute for running them on a computer. Such computers abound, and new ones appear constantly—which means that anything we might say about them would be inaccurate by the time you read these words. Therefore, if you do not yet know how to compile and execute a C++ program, please visit http://www.acceleratedcpp.com and see what we have to say there. We will update that website from time to time with information and advice about the mechanics of running C++ programs. The site also offers machine-readable versions of some of the example programs, and other information that you might find interesting.
Acknowledgments
We would like to thank the people without whom this book would have been impossible. It owes much of its form to our reviewers: Robert Berger, Dag Brück, Adam Buchsbaum, Stephen Clamage, John Kalb, Jeffrey Oldham, David Slayton, Bjarne Stroustrup, Albert Tenbusch, Bruce Tetelman, and Clovis Tondo. Many people from Addison-Wesley participated in its publication; the ones we know about are Tyrrell Albaugh, Bunny Ames, Mike Hendrickson, Deborah Lafferty, Cathy Ohala, and Simone Payment. Alexander Tsiris checked the Greek etymology in §13.2.2/236. Finally, the idea of starting with high-level programs grew over many years, stimulated by the hundreds of students who have sat through our courses and the thousands of people who have attended our talks.
Andrew Koenig Gillette, New Jersey
Barbara E. Moo June 2000
The C++ standard does not tell us exactly what a standard header is, but it does define each header's name and behavior. Including a standard header makes the associated library facilities available to the program, but exactly how the implementation does so is its concern, not ours.
0.3 The main function
A function is a piece of program that has a name, and that another part of the program can call , or cause to
a program, it does so by calling this function.
implementation whether the program ran successfully. A zero value indicates success; any other value means there was a problem. Accordingly, we begin by writing
int main()
function receives from the implementation. In this particular example, there are no parameters, so there is nothing between the parentheses. We'll see how to use main's parameters in §10.4/179.
0.4 Curly braces
We continue our definition of the main function by following the parentheses with a sequence of statements enclosed in curly braces (often simply called braces):
int main() { // left brace // the statements go here } // right brace
In C++, braces tell the implementation to treat whatever appears between them as a unit. In this example,
end. In other words, the braces indicate that all the statements between them are part of the same function.
When there are two or more statements within braces, as there are in this function, the implementation executes them in the order in which they appear.
0.5 Using the standard library for output
The first statement inside the braces does our program's real work:
std::cout << "Hello, world!" << std::endl;
implementation uses for ordinary output from programs. In a typical C++ implementation under a windowing
window.
more output, that output would appear on a new line.
0.6 The return statement
A return statement, such as
return 0;
that is returned must have a type that is appropriate for the type that the function says it will return. In the
implementation.
Of course, there may be more than one point at which it might make sense to terminate a program; such a
appropriate type.
0.7 A slightly deeper look
This program uses two additional concepts that permeate C++: expressions and scope. We will have much more to say about these concepts as this book progresses, but it is worthwhile to begin with some of the basics here.
An expression asks the implementation to compute something. The computation yields a result , and may also have side effects -that is, it may affect the state of the program or the implementation in ways that are
effects, and
std::cout << "Hello, world!" << std::endl
current line.
Every operand has a type. We shall have much more to say about types, but essentially, a type denotes a data structure and the meanings of operations that make sense for that data structure. The effect of an operator depends on the types of its operands.
characters enclosed in double quotes; may not span lines
must appear on a line by themselves (except for comments)
Types define data structures and operations on those data structures. C++ has two kinds of types: those built
Namespaces are a mechanism for grouping related names. Names from the standard library are defined in
We'll see more about string literals in §10.2/176 and §A.2.1.3/302.
Definitions and headers: Every name that a C++ program uses must have a corresponding definition. The
practice.
Braces and semicolons: These inconspicuous symbols are important in C++ programs. They are easy to overlook because they are small, and they are important because forgetting one typically evokes compiler diagnostic messages that may be hard to understand.
A sequence of zero or more statements enclosed in braces is a statement, called a block , which is a request to execute the constituent statements in the order in which they appear. The body of a function must be enclosed in braces, even if it is only a single statement. The statements between a pair of matching braces constitute a scope.
An expression followed by a semicolon is a statement, called an expression statement , which is a request to execute the expression for its side effects and discard its result. The expression is optional; omitting it results in a null statement , which has no effect.
Exercises
0-1. What does the following statement do?
0-2. Write a program that, when run, writes
This (") is a quote, and this () is a backslash.
different ways. Experiment with your implementation to learn how it treats tabs.
0-5. Is this a valid program? Why or why not?
#include
0-6. Is this a valid program? Why or why not?
#include
0-7. What about this one?
#include
int main() { /* This is a comment that extends over several lines because it uses /* and */ as its starting and ending delimiters */ std::cout << "Does this work?" << std::endl; return 0; }
0-8. ...and this one?
#include
0-9. What is the shortest valid program?
in the program.
The first statement,
std::cout << "Please enter your first name: ";
should be familiar by now: It writes a message that asks for the user's name. An important part of this
output does not begin a new line after the program has written its message. Instead, as soon as it has written the prompt, the computer waits-on the same line-for input. The next statement,
std::string name; // define name
returns any memory that the variable occupied to the system for other uses. The limited lifetime of local variables is one reason that it is important to distinguish between variables and other objects.
Implicit in the type of an object is its interface -the collection of operations that are possible on an object of
Once we have defined name, we execute
std::cin >> name; // read into name
The input operation has another side effect: It causes our prompt, which asks for the user's name, to appear on the computer's output device. In general, the input-output library saves its output in an internal data structure called a buffer , which it uses to optimize output operations. Most systems take a significant amount of time to write characters to an output device, regardless of how many characters there are to write. To avoid the overhead of writing in response to each output request, the library uses the buffer to accumulate the characters to be written, and flushes the buffer, by writing its contents to the output device, only when necessary. By doing so, it can combine several output operations into a single write.
There are three events that cause the system to flush the buffer. First, the buffer might be full, in which case the library will flush it automatically. Second, the library might be asked to read from the standard input stream. In that case, the library immediately flushes the output buffer without waiting for the buffer to become full. The third occasion for flushing the buffer is when we explicitly say to do so.
our user will see the prompt.
Our next statement, which generates the output, explicitly instructs the library to flush the buffer. That statement is only slightly more complicated than the one that wrote the prompt. Here we write the string
the output stream immediately.
Flushing output buffers at opportune moments is an important habit when you are writing programs that might take a long time to run. Otherwise, some of the program's output might languish in the system's buffers for a long time between when your program writes it and when you see it.
1.2 Framing a name
So far, our program has been restrained in its greetings. We'd like to change that by writing a more elaborate greeting, so that the input and output look like this:
Please enter your first name: Estragon
lines, respectively.
A sensible strategy is to build up the output a piece at a time. First we'll read the name, then we'll use it to construct the greeting, and then we'll use the greeting to build each line of the output. Here is a program that uses that strategy to solve our problem:
// ask for a person's name, and generate a framed greeting #include
int main() { std::cout << "Please enter your first name: "; std::string name; std::cin >> name;
// build the message that we intend to write const std::string greeting = "Hello, " + name + "!";
// build the second and fourth lines of the output const std::string spaces(greeting.size(), ' '); const std::string second = "* " + spaces + " *";
// build the first and fifth lines of the output const std::string first(second.size(), '*');
// write it all std::cout << std::endl; std::cout << first << std::endl; std::cout << second << std::endl; std::cout << "* " << greeting << " *" << std::endl; std::cout << second << std::endl; std::cout << first << std::endl;
return 0; }
So, for example, if we were to define
std::string stars(10, '*');
The rest of the program should be familiar; all it does is write strings in the same way we did in §1.1/9.
1.3 Details
Types:
Built-in type that holds ordinary characters as defined by the implementation.
Built-in type intended to hold "wide characters," which are big enough to hold characters for languages such as Japanese.
a character that is not whitespace. Then reads successive characters
Variables can be defined in one of three ways:
std::string hello = "Hello"; // define the variable with an explicit initial value
std::string stars(100, '*'); // construct the variable // according to its type and the given expressions
std::string name; // define the variable with an implicit initialization, // which depends on its type
Variables defined inside a pair of curly braces are local variables/which exist only while executing the part of
value, will not change during its lifetime. Such a variable must be initialized as part of its definition, because there is no way to do so later.
allow chained input operations.
1-0. Compile, execute, and test the programs in this chapter.
1-1. Are the following definitions valid? Why or why not?
const std::string hello = "Hello"; const std::string message = hello + ", world" + "!";
1-2. Are the following definitions valid? Why or why not?
const std::string exclam = "!"; const std::string message = "Hello" + ", world" + exclam;
1-3. Is the following program valid? If so, what does it do? If not, why not?
#include
int main() { { const std::string s = "a string"; std::cout << s << std::endl; }
{ const std::string s = "another string"; std::cout << s << std::endl; } return 0; }
#include
int main() { { const std::string s = "a string";