• Tidak ada hasil yang ditemukan

Accelerated c++ practical programming by example

N/A
N/A
Steven Love

Academic year: 2023

Membagikan "Accelerated c++ practical programming by example"

Copied!
453
0
0

Teks penuh

The results were dramatic: After one day in class, our students were able to write programs that would have taken them most of a week in the old course. Of course, many of the syntactic details will be familiar, but they are just details. By ignoring those parts of the language until the second part of the book, we make it possible to write useful C++ programs much faster than if we had adopted a more conventional approach.

The two appendices summarize and explain the important parts of the language and library in a level of detail that we hope will be useful in writing programs. The site also offers machine-readable versions of some sample programs and other information you may find interesting.

Getting started

  • Comments
  • The main function
  • Curly braces
  • The return statement

The only part of the standard library that our program uses is input-output, which we request via script. The left operand of the second << is therefore an expression that returns std::cout, which has type std::ostream; the right operand is std::endl, which is a manipulator. To the left of the :: is the (possibly qualified) name of a scope, which in the case of std::cout is the namespace called std.

To the right of :: is a name that is defined in the scope named to the left. In particular, newlines (that is, the way in which the implementation represents the change from one line of the program to the next) are just another type of space and usually have no special additional meaning.

Working with strings

Input

Here we write the string literal "Hello", followed by the value of the string variable name, and finally by std::endl. It uses the spaces variable to define a variable called second, which will contain the second line of output, and then the program constructs first as a variable containing as many * characters as the number of characters per second. Doing this promises that we won't change the value of the variable for the rest of its life.

Defines t as a variable of type std::string that initially contains a copy of the characters in s, where s can be either a string or a string literal. The result of this expression is a std:: string containing a copy of the characters in s followed by a copy of the characters in t.

Looping and counting

The problem

Overall structure

  • The while statement
  • Designing a while statement
    • if statements
    • Logical operators
  • Writing nonborder characters
  • Abbreviating repeated uses of std
  • Using for statements for compactness
  • Collapsing tests
  • The complete framing program

If you do that, the invariant becomes true at the end of the body, so we've satisfied the second requirement. For example, if r is zero, we know from the invariant that we haven't written any rows yet, which means we're writing part of the first row. Similarly, if r equals rows - 1, we know we've already written rows - 1 rows, so we now need to write part of the last row.

In the second form of the if statement, if the condition is false, then the program executes the following else statement. The while body adjusts the value of the variable so that eventually the condition fails.

Working with batches of data

Computing student grades

  • Testing for end of input
  • The loop invariant
  • Storing a collection of data in a vector
  • Generating the output
  • Some additional observations

The next section of code defines the variables we'll use to store the information we're about to read. A successful execution of cin >> x makes the first part of the invariant—the part that says we read the grade count—false. Whenever we define a vector, we must specify the type of values ​​that the vector will contain.

For now, it's important to realize that we can separate what it means to be a vector from the particular type of objects that the vector contains. That is, we can use the name vec_sz as a synonym for the size type until the end of the current scope. We begin by dividing the magnitude by 2 to find the center of the vector.

If they are even, the median is the average of the two elements closest to the middle. If the condition is true, then the result is the value of the expression between the . So, if we read an even number of elements, we set the median to the average of the two middle elements.

2.6/30, the first element of the vector named homework is homework[0], and the last element is homework[size - 1]. Assume that we have read some of the values ​​so far, and that we have no idea how many more values ​​need to be read. Proving that we cannot afford to throw away any of the values ​​we have read.

Organizing programs and data

Organizing computations

  • Finding medians
  • Reimplementing our grading policy
  • Reading homework grades
  • Three kinds of function parameters
  • Using functions to calculate a student's grade
  • Keeping all of a student's data together
  • Managing the student records
  • Generating the report

Not only must we provide arguments that match the parameters of the functions we call, but we must provide them in the same order. The first point is the type, const vector&, which we specify for the third argument. The idea that we can have multiple functions with the same name is called overloading, and figures prominently in a lot of C++.

In the first case, our caller will think that we have reached the end of the file. These requirements mean that we need a place to store all students' information so that we can alphabetize them. Assuming we have a place to store the data about a single student, we can use a vector to store all the student data.

The function that reads one of our records is very similar to the read_hw function we wrote. When we use the s parameter inside the function, we will affect the state of the argument we are given. We start by putting the media function definition in a separate file so we can compile it separately.

The simple answer is that we need to write a declaration for the median function, which we do by replacing the function body with a semicolon. We include the vector header so we can use the name std::vector to declare the argument to median. Student_info type and declarations for the functions that we use to manipulate Student_info objects and generate grades.

Using sequential containers and analyzing strings

Separating students into categories

  • Erasing elements in place
  • Sequential versus random access
  • Iterator types
  • Iterator operations
  • Some syntactic sugar
  • The meaning of students.erase (students.begin () + i)
  • Some important differences
  • Why bother?
  • Framing a picture
  • Vertical concatenation
  • Horizontal concatenation

Recall that students.begin() returns a value indicating the initial element of the vector—the one at index 0. For example, fgrade(students[i]) retrieves the ith element of the vector named students and passes that element to the fgrade function. All we need to know is that vector has a member named const_iterator that defines a type that we can use to get read-only access to the vector's elements.

What is useful to know now is that start and end functions return a value of the iterator type for the container. All we need to know is that afterwards the iterator specifies the next element in the container. In the body of for, iter is placed on an element in the students, which element we have to write.

By writing (*iter).name we are saying that we want to refer to the name member of the *iter object. So many of the techniques we can apply to vectors also apply to strings. The call to push_back uses a string class member called substr that we haven't seen before.

This fact implies that we will need a function to find the length of the longest string in the vector. Each rotation puts the next word of the input in the first position and rotates the previous first word 1. In the hcat function of what would happen if we defined s outside the scope of the while.

Using library algorithms

Analyzing strings

  • Another way to split
  • Palindromes
  • Finding URLs
  • Working with student records
  • Analyzing the grades
  • A two-pass solution
  • A single-pass solution

We use typedef to shorten the iterator type, so we can use iter instead of the longer string::const_iterator. If url_beg finds a URL, the next task is to find the end of the URL by calling url_end. Local variables declared static are preserved across calls to the function.

As with find_if, if the value we want is present, the function returns an iterator indicating the first occurrence of the value in the given sequence. First we check if the separator is at the beginning or end of the entry. This function looks in s.homework to see if any of the values ​​stored there are 0.

A string representing the name of the analysis The function to use for the analysis. We should now be able to see that the effect of the remove_copy call is to copy all the non-zero elements of s.homework to non-zero. What it really does is copy to the beginning of the sequence the elements that do not satisfy the predicate.

Each of these algorithms returns an iterator representing the first element of the second section. We construct fail from a copy of the failing records, which are in the range [iter, students.end()), and then delete those elements from students. Instead, it copied every element for which the predicate was false before the students started, and left the rest of the elements alone.

Using associative containers

Containers that support efficient look-up

  • Representing the rules
  • Reading the grammar
  • Generating the sentence
  • Selecting a random element

As with other containers, we need to specify the type of objects the map will hold. When we reference a map iterator, we get a value that is of the type of the pair associated with the map. The iterator points to an element of words, and so *is one of the words in the input line.

The rest of the program writes the contents of the data structure that split returns. Most of the program is the pre-declaration, the form of which should be known from §7.2/124. When reading the body in the for loop, remember that from references a map iterator returns a value of type pairs.

The first element of the pair holds the key (const), and the second element is the value associated with that key. Then the while loop iterates through the remaining elements (if any) of the vector. Dereferencing this iterator returns a pair whose second member is the value of the map element.

The only even slight complexity is that we put a space before the second and subsequent words of the sentence. For each key type, someone must provide a hash function, which calculates an appropriate integer value from the value of the key. Value initialization: Accessing a map element that does not yet exist creates an element with a value of V(), where V is the type of values ​​stored in the map.

Referensi

Dokumen terkait