Summary of C ++ primer Chinese edition (fourth edition) (1)

Source: Internet
Author: User
Tags array definition bitset

Recently, I decided to review Lippman's masterpiece "C ++ primer", record some important knowledge points during the Query Process, and hope to help myself. For ease of query, all content is classified by chapter.

Chapter 1 Quick Start

1. The iostream library is based on the two types named istream and ostream, indicating the input stream and output stream respectively.

The standard library defines four IO objects and uses the istream type object of CIN when processing input. When processing the output, use an ostream object named cout. The cerr object used to process standard errors to output warning and error messages to the program. A clog object that generates general information about program execution.

2. Read unknown object input: Use the while statement to judge until the file end character (CTRL + Z) is encountered)

While (STD: CIN> value) <br/> sum + = value;

Chapter 2 variables and Basic Types

1. Copy initialization and direct Initialization

Int ival (1024); // directly initialize <br/> int ival = 1024; // copy Initialization

2. Initialization is not a value assignment: initialization is to create a variable and assign it an initial value, while the value assignment is to erase the current value of the object and replace it with a new value.

3. Declaration and definition: the definition of a variable is used to allocate storage space for the variable. You can also specify the initial value for the variable. In a program, the variable has only one definition; declaration is used to indicate the type and name of a variable to the program. definition is also Declaration: when defining a variable, we declare its type and name. You can use the extern keyword to declare a variable name without defining it.

Extern int I; // declare but not define <br/> int I; // declare and define I

4. constants must be initialized during definition. constants cannot be modified after definition, so they must be initialized.

Const string HI = "hello"; // true: initialization <br/> const int I; // error: I is uninitialized const

5. const reference: When a const reference is executed, the reference of the const object is executed.

Const int ival = 1024; <br/> const Int & refival = ival; // OK: both reference and object are const <br/> Int & refival2 = ivale; // error: nonconst reference to a const object

6. The only difference between defining a class with the class and struct keywords lies in the default access level. By default, struct members are public, while Class Members are private.

Chapter 3 Standard Library types

In addition to the basic data types, C ++ also defines a standard library of rich abstract data types. The most important standard library types are string and vector, which define variable-size strings and sets respectively. Another standard library type bitset provides an abstract method for bitwise sets. This chapter describes the vector, string, and bitset types in the standard library.

1. Definition and initialization of string type objects

# Include <string> <br/> Using STD: string; </P> <p> string S1; <br/> string S2 (S1 ); <br/> string S3 ("value"); <br/> string S4 (n, 'C ');

2. to be compatible with the C language, the string literal value is not of the same type as the string type in the standard library, so be sure to differentiate it during programming. When the string object and the string literal value are joined together, at least one of the left and right operators of the + operator must be of the string type.

String S1 = "hello"; <br/> string S2 = "world"; <br/> string S3 = S1 + ","; // OK <br/> string S4 = "hello" + ","; // error <br/> string S5 = S1 + S2; // OK <br/>

3. # include <cctype. h> processes a single character in the string object.

4. Vector type in the standard library

# Include <vector> <br/> Using STD: vector; </P> <p> vector <t> V1; <br/> vector <t> V2 (V1 ); <br/> vector <t> V3 (n, I); <br/> vector <t> V4 (n); </P> <p> v. empty (); // returns true if V is null <br/> v. size (); // returns the number of elements in v <br/> v. push_back (t); // Add an element whose value is t at the end of v.

5. Only subscript operations can be performed on elements that are known to exist:

Vector <int> ivec; <br/> cout <ivec [0]; // error: ivec has no elements </P> <p> vector <int> ivec2 (10); <br/> cout <ivec2 [10]; // error: ivec has elements 0... 9

6. In addition to using subscript to access elements of a vector object, the standard library also provides another method for accessing elements: using the iterator, an iterator is a data type that checks elements in a container and traverses elements.

Vector <int>: iterator ITER;

7. begin and end operations:

Vector <int>: iterator iter = ivec. begin (); // points to the first element <br/> vector <int>: iterator iter = ivec. end (); // The iterator returned by the end operation points to the "next end element" of the vector"

8. Difference Between the unreferenced operator * and the submark

For (vector <int >:: size_type IX = 0; ix! = Ivec. size (); ++ IX) <br/> ivec [ix] = 0; </P> <p> for (vector <int >:: iterator iter = ivec. begin (); iter! = Ivec. End (); ++ ITER) <br/> * iter = 0;

9. Each container type also defines a type named const_iterator. This type can only be used to read elements in the container, but cannot change its value. When using the const_iterator type, we can get an iterator whose own value can be changed, but it cannot be used to change the value of the element to which it points.

For (vector <string >:: const_iterator iter = text. Begin (); iter! = Text. end (); ++ ITER) <br/> cout <* ITER <Endl; // print each element in text </P> <p> for (vector <string >:: const_iterator iter = text. begin (); iter! = Text. End (); ++ ITER) <br/> * iter = ""; // error: * ITER is const </P> <p>

10. Do not confuse the const_iterator object with the const iterator object. When declaring a const iterator, The iterator must be initialized. Once initialized, its value cannot be changed.

Vector <int> Nums (10); // Nums is nonconst <br/> const vector <int>: iterator CIT = nums. begin (); <br/> * CIT = 1; // OK: CIT can change its underlying element <br/> ++ cit; // error: can't change the value of CIT

11. Reverse conversion is performed between the string object and the bitset object: the rightmost character of the string object is used to initialize the low-level bit of the bitset object. Remember this difference when initializing a bitset object with a string object. If the number of characters of the string object is smaller than the length of the bitset type, the higher order is 0.

String strval ("1100"); <br/> bitset <32> bitvec (strval); // In bitvec bit mode, the positions 2nd and 3 are 1, and the remaining positions are 0.

Chapter 4 arrays and pointers

The C ++ language provides two low-level composite types similar to the vector and iterator types-arrays and pointers. Modern C ++ programs should try to use vector and iterator types, instead of low-level arrays and pointers, well-designed programs only use arrays and pointers within the class implementation when speed is emphasized. Compared with the vector type, an array has a significant defect: the length of the array is fixed, and the programmer cannot know the length of a given array. The array does not obtain the size of its capacity, the push_back operation is not provided to automatically add elements in the operation. If you need to change the length of the array, the programmer can only create a larger new array, and then copy all elements of the original array to the new array space.

1. array definition and initialization: the dimension of the array must be defined using a constant expression with a value greater than or equal to 1, this constant expression can only contain an integer literal value constant, an enumerated constant, or an integer const object initialized using a constant expression. Non-const variables and const variables whose values are not known at the running stage cannot be used to define the dimension of the array.

Const unsigned buf_size = 512, max_files = 20; <br/> int staff_size = 27; <br/> const unsigned SZ = get_size (); </P> <p> char input_buffer [buf_size]; // OK, const variable <br/> string filetable [max_files + 1]; // OK, constant expression <br/> double salaries [staff_size]; // error: non const variable <br/> int test_scores [get_size ()]; // error: the value is known only when the function is called at run time. non const expression <br/> int Vals [SZ]; // error: size not konwn until Run Time

2. Directly copying and assigning values to Arrays: Unlike vector, an array cannot be initialized with another array or assigned to another array.

Int Ia [] = {0, 1, 2}; <br/> int ia2 [] (IA); // error: cannot be initialized with another array </P> <p> const unsigned array_size = 3; <br/> int ia3 [array_size]; // OK, but elements are uninitialized <br/> ia3 = IA; // error: An array cannot be assigned to another array.

3. The length of the array is fixed: Unlike the vector, the array does not provide push_back or other operations to add new elements to the array. Once defined, new elements cannot be added to the array.

4. Vector traversal can be implemented by subscript or iterator. Likewise, you can use a subscript or pointer to traverse an array. The Pointer Points to a type of object that meets the data type, it is an iterator used for arrays. It points to an element in the array and uses the unreferenced operator * and the auto-incrementing operator ++ on the pointer to an array element, similar to the usage on the iterator.

String S ("helloworld"); <br/> string * sp = & S; // defines a pointer to the string type sp

5. Read the pointer declaration statement from right to left.

String * pstring; // define pstring as a pointer variable pointing to a string type object </P> <p> double DP, * dp2; // This statement defines a double type DP object and a pointer to a double type object dp2 </P> <p> string * pS; // define PS as a pointer to a string object </P> <p> string * ps1, pS2; // PS1 is defined as a pointer, pS2 is not a pointer, it's just a common string object. </P> <p> string * ps1, * PS2; // defines two pointers.

6. Constraints on Pointer initialization and assignment. Only the following four types of values can be used for pointer initialization or assignment: (1) 0 value constant expression (2) type matching object address (3) next address after another object (4) another valid pointer of the same type. It is invalid to assign the int type variable to the pointer.

Int ival; <br/> int zero = 0; <br/> const int c_ival = 0; <br/> int * Pi = ival; // error: pi initialized from int value of ival <br/> Pi = zero; // errro: PI assigned int value of zero <br/> Pi = c_ival; // OK: c_ival is a const with compile time value of 0 <br/> Pi = 0; // OK: directly initialize to literal constant 0

7. Void * pointer: it can save the address of any type of object: void * indicates that the pointer is related to an address value, but it is unclear about the type of the object stored on this address, the void * pointer only supports several limited operations: compare it with another pointer; pass the void * pointer to the function or return the void * pointer from the function; assign a value to the other void * pointer. You cannot use the void * pointer to operate the object to which it points.

Double OBJ = 3.14; <br/> double * Pd = & OBJ; <br/> void * Pv = & OBJ; <br/> Pv = Pd;

8. The pointer provides the function to indirectly manipulate the objects it refers to. Just like the iterator for unreferencing, the pointer can be used to access the objects it refers.

String S ("Hello World"); <br/> string * sp = & S; // SP holds the address of S <br/> cout <* sp; // print Hello World

9. For comparison between pointers and references, although both references and pointers can indirectly access another value, there are two important differences between them:

The first difference is that the reference always points to an object, and it is wrong to define the reference without initialization; the second is the difference between the assignment behavior, assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object. Once the reference is initialized, it always points to the same specific object.

// After the assignment is complete, the value of the ival object pointed to by PI remains unchanged <br/> int ival = 1024, ival2 = 2048; <br/> int * Pi = & ival, * Pi2 = & ival2; <br/> Pi = Pi2; // PI now points to ival2 </P> <p> // This value assignment operation modifies the value ival object referenced by Ri, instead of referencing itself <br/> Int & rI = ival, & ri2 = ival2; <br/> rI = ri2; // assigns ival2 to ival <br/>

10. pointer to pointer: C ++ uses the ** operator to assign a pointer to another pointer. To truly access the ival object, the PPI must be unbound twice.

Int ival = 1024; <br/> int * Pi = & ival; // PI points to an int <br/> int ** PPI = π // pointer to the pointer </P> <p> cout <** PPI <Endl; // obtain the value of ival for two decommission operations

11. pointer and const qualifier

(1) pointer to the const object: The following cptr is a pointer to the double-type const object. Const limits the object type pointed to by the cptr pointer, not the cptr itself. That is to say, cptr itself is not a const. If necessary, you can assign a value to cptr to point it to another const object, but you cannot modify the value of the object it refers to through cptr. At the same time, assigning the const object address to a normal non-const object pointer will also cause compilation errors. You cannot use the void * pointer to save the const object address.

Const double * cptr; // cptr may point to a double that is const </P> <p> const double Pi = 3.1415; <br/> double * PTR = & PI; // error: PTR is a plain point <br/> const double * cptr = & PI; // OK <br/> * cptr = 42; // error: * cptr might be const </P> <p> const int universe = 42; <br/> const void * CPV = & universe; // OK: CPV is const <br/> void * Pv = & universe; // error: the address of the const object cannot be saved using the void * pointer </P> <p> double dval = 3.14; <br/> cptr = & dval; // allows you to assign non-const object addresses to pointers to const objects.

(2) const pointer: The value cannot be modified. The following curerr is the const pointer to the int type object. The value of the const pointer cannot be modified, which means that curerr cannot be directed to other objects, any attempt to assign a value to the const pointer will cause compilation errors.

Int errnumb = 0; <br/> int * const curerr = & errnumb; // curerr is the const pointer </P> <p> curerr = curerr; // exception: the const pointer value cannot be modified.

(3) const pointer to the const object: neither the value of the object pointed to by pi_ptr can be modified nor the pointer to be modified.

Const double Pi = 3.1415926; <br/> const double * const pi_ptr = PI ;//

12. pointer and typedef, as shown in the following code, what type is the CSTR variable?

Typedef string * pstring; <br/> const pstring CSTR;

Generally, CSTR is a pointer of the const pstring type. What is the actual type indicated by the const pstring pointer? Note that it is not a string-type const object (typedef cannot be used as a text extension), but a const pointer to a string-type object, because const modifies the pstring type.

13. C-style string: character array ending with null

Char cal1 [] = {'C', '+', '+'}; // not a C-style string <br/> char cal2 [] = {'C ', '+', '+', '/0'}; // C-style string <br/> char cal3 [] = "C ++"; // automatically add null, is a C-style string

14. Standard library functions of C-style strings must contain the corresponding C header file # include <cstring>

Strlen (s); // returns the length of S, excluding the string Terminator null <br/> strcmp (S1, S2); // compares whether the two strings S1 and S2 are the same. <Br/> strcat (S1, S2); // connect string S2 to S1, and return S1 <br/> strcpy (S1, S2 ); // copy S2 to S1 and return S1 <br/> strncat (S1, S2, n); // connect the first n characters of S2 to the end of S1, return S1 <br/> strncpy (S1, S2, n); // copy the first n characters of S2 to S1, and return S1

15. dynamically defining arrays and initializing Arrays: You can use a pair of empty parentheses following the array length to initialize the values of array elements.

Int * Pia = new int [10]; // an array containing 10 int elements is allocated. <br/> int * pia2 = new int [10] (); // set all array elements to 0 </P> <p> const int * pci_bad = new const int [100]; // error: uninitialized const array <br/> const int * pci_ OK = new const int [100] (); // OK: value-initialized const Array

16. The C language uses a pair of standard library functions malloc and free to allocate storage space in the free storage area, while the C ++ language uses the new and delete expressions to implement the same functions. Pay attention to the release of dynamic space. The empty square brackets between the keyword Delete and pointer are required. It tells the compiler that the pointer points to an array in the free storage area, rather than a single object.

Delete [] PIA; // This statement recycles the array referred to by Pia.

17. The string class provides a member function named c_str to return a C-style string, that is, a pointer to the first address of the character array, which stores the same content as the string object, end with the terminator null.

String STR ("Hello World"); <br/> char * str1 = STR; // error <br/> char * str2 = Str. c_str (); // OK

Chapter 5 expressions

This chapter focuses on the operators defined in the C ++ language. They use built-in type operands.

1. sizeof OPERATOR: returns the length of an object or type name. The returned type is size_t. The length is in bytes and has the following syntax formats:

Sizeof (type name); <br/> sizeof (expr); <br/> sizeof expr;

2. Forced conversion: dynamic_cast (supports identifying pointers or referencing objects to be pointed to during runtime) and const_cast (converts the const nature of expressions), static_cast (any data type implicitly implemented by the compiler can be explicitly completed by it), reinterpret_cast (usually provides a lower-level re-interpretation for the bit mode of the operand)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.