C + + Primer Puls Learning notes (ii)

Source: Internet
Author: User
Tags array length first string

I. Review of knowledge points

1 , Arrays ( Array )

( 1 ) The basic information of the array

An array is a data format that can store multiple types of values, declare an array, and use a declaration statement, but it should contain the following three points:

Array name

The type of the value stored in each element

The number of elements in the array

The common format for array declarations is as follows:

TypeName Arrayname [ArraySize]

ArraySize must be an integer or const value, or it can be a constant expression (specifically, it cannot be a variable).

(2) Array Number

Many uses of arrays are used to access individual array elements, the C + + array is numbered from 0, and the index is used to identify access to individual elements.

Ex:int Moths[12]

Moths[0] is the first element of a moths array.

(3) Array Declaration Note :

The initialization can only be used if the array is defined, and thereafter it cannot be used and cannot be assigned to another array;

When initializing an array, the supplied value can be less than the number of elements in the array, and the compiler will set its element to 0 for the initialized part.

(4) c++11 initialization method for arrays in

You can omit the equals sign when initializing an array.

You can have nothing inside the curly braces, all elements are set to 0.

List initialization, which prohibits narrowing conversions.

2 , String (String)

(1) C- style of String

C-style strings are stored in a char array, ending with ' \ n ' (null character);

Character constants use single quotes, string constants use double quotation marks, and are not interchangeable with each other;

Stitching string constants, null characters in the first string will be replaced by the second string

( 2 ) to use strings in the array

You can use initialization string constants or input keyboard files into an array;

sizeof returns the length of the entire array;

Strlen returns the length of the visible string in the array, and does not calculate the null character, so it is +1 when determining the length of the array;

( 3 ) string Input

Using cin for string input, CIN uses whitespace (space, tab, \ n) to determine the end position of the string.

Ex:cin >> Mia WANG;

CIN treats Mia as the first string, and automatically adds null characters at the end, ending with Wang.

The input string may be more than the target number leader, and only the string of the target array length is truncated.

( 4 ) reads a line of string input each time

A , line-oriented input: getline ()

The Getline () function, which determines the end of the input by a newline character entered by the Enter key;

Call the function using Cin.getline ();

The function has two parameters, the first is the array name, the second is the number of strings to read;

Ex:cin.getline (Arraynanme, arraysize);

The getline () member function stops reading when reading a set number of characters or into a newline character, and then replaces the line break with null characters.

B , line-oriented input: Get ()

The Get () function works similarly to the getline () function, except that the get () function reads to the end of the line, no longer reads and discards the line feed, but leaves it in the input queue;

After the first throw, the newline character will remain in the input queue, the second call, see the first character is a newline, get () function think has reached the end of the team, will not continue to read the content;

Using Cin.get () without any parameters can read the next character (the newline character), so it can be used to handle line breaks and be prepared for reading the next line of input.

Ex:cin.get (Name1, size);

Cin.get ();

Cin.get (Name2, size);

Another way to use this is to stitch together two class member functions;

Ex:cin.get (Name1, size). get ();

Cin.getline (Name1, size). getline (Name2, size);

3 , string class

( 1 ) string Class Introduction

You can use a variable of type string instead of a character array to store the string, and the string class is simpler to use than an array, and provides a representation of the string as a data type.

To use the string class, you must include the header file name <string>;

The string class is located in the namespace STD, and must be supplied with a using compiler directive, or by using the std:: string to reference;

The string class definition hides the nature of the string array and can handle the string as if it were a normal variable;

A, a C-style string can be used to initialize a string object;

Ex:string str1;

String str2 = "Panther";

You can use CIN to store keyboard input in a string object;

Ex:cin >> str1;

You can use the Cout object to display a string object;

Ex:cout << str1;

You can use array notation to access the characters stored in a string object.

( 2 ) C + + string initialization, assignment, stitching, and attaching

C + + string initialization and array are the same;

You can assign a string class object to another object;

Ex:string str1;

String str2 = "Panther";

STR1 = str2;

You can use the "+" operator to stitch two string classes;

You can use the "+ =" operator to append a string to the end of a string object.

( 3 ) string Other operations of the class

strcpy (CHARR1, CHARR2)//copy charr2 to CHARR1;

strcat (CHARR1, CHARR2)//oppend contents charr2 to charr1;

Strlen (Charr) and Str.size ()

A, strlen () is a regular function that accepts a C-style string as a parameter;

Ex:strlen (CHARR1);

b, Size () is a method of the string class, using the "." operator to invoke this method;

Ex:str.size ();

(4) string class I/O

Uninitialized array contents are undefined;

The length of the string class object that is not initialized is automatically set to 0;

Cin.getline (arrayname, size) ≠getline (CIN, str);

Cin.getline () is a IStream class method that accepts two parameters, a target array, and an array length;

Getline () is a function that accepts two parameters, cin and string names, Cin indicates where to look for the input, and no arguments for the length of the string, and the string object is automatically resized based on the length of the string.

4 , Structure

( 1 ) Structure Introduction

A structure is a more flexible data format than an array that can store a variety of data types (such as storing int, float, double together) to merge the representation of the data together, and it is also the cornerstone of the class (OOP).

( 2 ) Declaration of the structure

The creation structure contains two points, defines the structure description and marks the various data types that can be stored in the structure;

Ex:struct Black

{

Char name[20];

float volume;

Double Price;

};

The struct keyword indicates that this is a structure;

Black is the name of this data format, and the new type is called black;

Inside the curly braces is a list of the data types of the structure, each of which is a declaration statement;

Each item in the list is called a struct member.

( 3 ) Create structural variables

The structure is created with the same name as the base type;

Ex:black Cat

The type of cat is black;

You can use member operators to access individual members and use them in the same way as regular type variables and to access array elements as if they were indexed;

Ex:cat.name; (equivalent to a variable of type char)

The position of the structure: the position of the struct declaration is called an external declaration outside the Mian () function, which can be used by the function behind it, and the internal declaration can only be used by the function to which the declaration belongs;

Initialization of the structure:

A, the initialization of the structure is the same as the array, using commas to separate the list of values, and the values are enclosed in curly braces;

b, each structure member can be regarded as the corresponding type of variable;

C, if the curly braces do not contain anything, each member will be set to zero;

D, the list can be initialized for the structure, and the equal sign is optional;

E, each struct member can be initialized to the appropriate type data;

F, narrowing conversions are not allowed.

Make the string class A struct member, make sure that the struct has access to the namespace STD, use the using compiler directive, or use "::".

Other properties of the structure:

A, structure can be passed as a parameter to a function, you can also let the function return a structure, you can also use the assignment operator to assign the structure to another structure of the same type;

b, you can complete the structure definition and create the structure variable at the same time, just put the variable name behind the closing parenthesis, or even, you can initialize the variables created in this way.

Ex:struct Black

{

Char name[20];

Double Price;

}cat, Dog;

Or:

Struct Black

{

Char name[20];

Double Price;

}cat

{

Tom,

35.5

};

Array of Structures:

The structure array is created in exactly the same way as the base type array method;

Ex:black gifts[100] is an array of 100 black structures in which each element of the array is the object of the black structure;

Bit fields in the structure:

C + + allows a struct member to occupy a specific number of bits, the field type should be an integer or an enumeration, followed by a colon, followed by a number that uses a number of digits.

5 , common body

A common body is a data format that can store different data types, but can only store one type at a time;

Declaration of a common body:

Ex:union One4all

{

In Int_val;

Long Long_val;

Double Double_val;

};

A common body can store different variables at different times of the condition (either storing an int or storing a long or storing a double);

The length of the common body is its maximum member length;

The primary use of a common body is to save space when data is used in two or more formats;

An anonymous common body does not have a name and its members become variables at the same address.

6 , Enumeration

(1) C + + enumeration provides another way to create symbolic constants, instead of const, and allows the definition of new types, but must be strictly restricted;

Ex:enum spectrum{red, Orange, yellow, green, blue, violet, indigo, ultraviolet};

It has completed the following two tasks:

A, let spectrum become the new type (enum) name;

b, red, orange, etc. as the symbolic constants, corresponding to the numeric 0~7, these constants are called enumeration constants.

Enumeration variables can be declared using enumerations:

Ex:spectrum Band;

In the case of no casting, only the enumeration used when defining the enumeration is assigned to this enumeration variable.

Ex:band = red;√

Band = 2000;x

The assignment operator is established for the enumeration, and no arithmetic operator is defined;

The enumerator is an integral type and can be promoted to an int type, but the int type cannot be automatically converted to an enumeration type;

If the int value is valid (such as the corresponding 0~7 in spectrum), it can be assigned to the enumeration variable by forcing the type conversion;

Ex:band = Spectrum (3) is equivalent to band = Green;

( 2 ) Sets the value of the enumeration amount

You can use the assignment operator to explicitly set the value of an enumerator (or some of its enumerated values) and the value must be an integer;

You cannot create multiple enumerators with the same value.

( 3 ) The range of values for the enumeration

The upper bound of the enumeration value is the power minus 1 of the minimum 2 greater than the maximum value of the enumerator;

The lower bound of the enumeration range is divided into two cases, if the minimum value is not less than 0, the lower bound is 0, the other is that the minimum value is less than 0, and its lower bound is less than the least 2 of the enumeration minimum value of the power minus 1.

7 , pointers, and free storage space

The computer program must keep track of 3 basic properties when storing data:

Where is the information stored?

What is the stored value?

What type of information is stored?

( 1 What is a pointer?

A pointer is a variable that stores the address of a value, not the value itself;

Use the "&" address to get the address of a regular variable (when using a regular variable, the value is a fixed amount, the address is derived, and the pointer is used exactly the opposite);

( 2 ) pointer and C + + Fundamentals

OOP emphasizes decision-making during runtime, traditional procedural programming emphasizes decision-making at compile-time, and OOP chooses repair tools according to the problem, while traditional procedural programming is more like providing a bunch of tools to solve problems.

So, OOP makes the program more flexible, in C + + , using the new keyword to request the correct amount of memory, using pointers to track the location of the newly allocated memory .

( 3 ) The representation of the pointer

The pointer name represents the address;

The * operator is referred to as the indirect value operator or dereference operator;

* operator applies to the pointer, you can get the value of the address value of the stored values;

(c + + determines whether a multiplication or dereference operator is referred to by the context)

Ex: Assuming that Manly is a pointer, then Manly represents an address;

* Manly The Manly pointer, indicating the value stored at the Manly address;

* Manly is equivalent to regular int variables;

The int variable and the pointer variable are just two sides of the same coin:

Ex:int dates = 30;

int * P_dates = &dates;

The regular variable dates represents the value and uses the & operator to obtain the address;

P_dates represents the address and uses the * operator to obtain the value;

* P_dates equivalent to dates;

P_dates equivalent to &dates;

( 4 ) Declaration and initialization Pointers

A, the computer needs to track the type of the value that the pointer points to, so the pointer declaration must make the data type pointed to by the pointer;

Ex:int * p_dates

P_dates is the pointer variable, which represents the address;

P_dates points to int type;

The type of p_dates is a pointer to type int (or int *, in C + + int * is a compound type, a pointer to int);

* The P_dates type is of type int, not a pointer.

b, you can initialize a pointer in a declaration statement, in which case the pointer is initialized, not the value it points to;

Ex:int * pt = &higgens;

Set the value of PT (not *pt) to &higgens.

( 5 ) risk of pointers

When C + + creates a pointer, the computer allocates memory to store the address, but does not allocate memory to store the data that the pointer points to, so be sure to initialize the pointer to a deterministic, appropriate address before applying the dereference operator to the pointer.

( 6 ) pointers and numbers

Pointers are not integers, so it is not possible to assign numbers to pointers simply;

Ex:int * PT;

Pt = 0xb8000000;

The C language allows such assignments, but in C + + The compiler will display type mismatches;

To use a numeric value as an address, you should convert the number to the appropriate address type by forcing the type conversion:

Ex:int * PT

Pt = (int*) 0xb800000;

Note: PT is an int type address and does not mean that PT is of type int.

( 7 ) using New to allocate memory

Regular variables are assigned a name memory value in the compile phase;

The pointer allocates an unnamed memory to store the value at run time, which is done using the new keyword;

Ex:int * pn = new int;

The new int tells the program that it needs the appropriate memory for storing int;

The new operator determines how many bytes of memory are required based on the type, then finds such memory and returns the address to the PN;

In the program, new is used in the following format:

TypeName * pointername = new TypeName;

Variables are stored in the stack;

New memory is allocated to the heap (free storage space).

( 8 ) Free Memory

Use the Delete keyword in C + + to free memory by adding a pointer to the memory block after the delete;

Ex:int * PS = new int;

... ...

Delete PS;

Delete releases the memory that the PS points to, but does not delete the PS itself;

New and delete are paired, otherwise a memory leak will occur;

Do not release the same block of memory two times;

You can only use Delete to release the memory allocated by new;

It is safe to use DELETE with a null pointer.

( 9 ) using New Creating dynamic Arrays

For small Data Objects (referred to as memory blocks allocated for data), the use of variables is undoubtedly a simpler way to send, but for large data objects, you should use new.

Static Binder: Allocates memory for arrays during the compilation phase;

Dynamic linking: Creating arrays at run time;

A, how to create an array with new and use pointers to access array elements:

A. Create a dynamic array with new:

Tell new The element type and the number of elements of the array;

Ex:int * psome = new INT[10];

A, the new operator returns the address of the first element of the array and assigns it to the pointer;

b, for arrays created with new, you should use delete [] to release;

c, the common format for allocating memory for arrays is as follows:

TypeName * pointername = new typename[num_elements];

New ensures that a block of memory is sufficient to store num_elements elements of type TypeName, Pointername points to the first element of the array.

B. Using dynamic arrays

Ex:int * psome = new INT[10];

Using dynamic arrays, just use pointers as array names (arrays and pointers are handled similarly in C and C + +, so arrays and pointers are basically equivalent);

( Ten ) pointer, array, and pointer arithmetic

Conversions between pointers and arrays:

Arrayname[i] becomes * (arrayname + i);

Pointername[i] becomes * (pointername + i);

EX:STACKS[1] equivalent to * (stacks + 1);

Difference 1: The value of the pointer can be modified, and the array name is constant;

Difference 2: Applying the sizeof operator to an array is the length of the arrays, and the length of the pointer is given by applying sizeof to the pointer.

( One ) Pointer Summary

A, the Declaration pointer:

TypeName * Pointername

B. Assign a value to the pointer:

The memory address should be assigned to the pointer, you can apply the & operator to the variable name to obtain a named memory address, new returns an unnamed address;

C, dereference the pointer

Dereference the pointer to get the value pointed to by the pointer, use * to dereference the pointer;

Never dereference a pointer that has not been initialized with an appropriate address;

D. Distinguish the values pointed to by pointers and pointers

If PT is a pointer to int, then *PT is not a pointer to int, but rather a variable of type int, PT is the pointer;

E, array name

In most cases, C + + treats the array name as the first element address of the array;

F, pointer arithmetic

pointer addition: C + + allows pointers and integers to be added, and the result of 1 equals the number of bytes in the system with the type of pointer pointing at the original address;

Subtraction of pointers: subtraction occurs only when the operation points to the same array (or to a position beyond the end of the array), and the result is the interval between two elements;

Static and dynamic linking of arrays

When you use an array declaration to create an array, the static union is used, and the array length is set at compile time;

Using the new[] operator to create an array is a dynamic union, with the array length set at run time;

F, array notation and pointer notation

Using the [] array notation is equivalent to dereferencing the pointer;

Ex:tacos[0] means *tacos

TACOS[3] means * (tacos + 3)

(a) Pointers and Strings

In cout and most C + + expressions, a char array name, a char pointer, a string constant enclosed in quotation marks, are interpreted as the address of the first character of a string;

Some compilers treat string literals as read-only constants and cause system errors if they attempt to modify them;

The use of the Const keyword means that strings can be accessed, but they cannot be modified;

Some compilers use only a copy of the string literal to identify all of the literal values in the program;

When the string is read into the program, the allocated memory address should be used;

In general, provide a pointer to cout, which will print the address, but if the pointer is of type char *, cout will display a pointer to the string, and the other type must be forced to convert to display the string;

Assigning an array to a pointer does not assign a value to the string, but only the address, so that two pointers point to the same memory address and string;

Two steps are required to get a copy of a string:

A, you need to allocate enough memory:

ex:string animal = "cat";

char * PS = new Char[strlen (animal) +1];

Use strlen to determine the length of the string, add 1, get the length that contains the null character, and then use new to get enough storage space;

B. Use the library function strcpy () to copy the strings in the array into the newly allocated space;

strcpy () accepts two parameters, the first destination address, and the second is the string address to copy;

ex:strcpy (PS, animal)

strncpy () accepts the third parameter, which is the maximum number of characters to copy, but be aware that if the function has exhausted the target memory before reaching the end of the string, it will not add a null character.

( - ) using New Create a dynamic structure

A, using new for the structure consists of two parts:

Create structures;

Access to its structural members;

B. Use new to create the structure:

Ex:struct thing

{

int good;

int bad;

};

Ting pen = {21, 32};

Thing * pt = &pen;

C. When you create a dynamic structure, you cannot use the period member operator for the struct name, and you must use the Arrow member operator (-) to access its members.

If the struct identifier is a struct name, the period member operator is used;

For pointers to structures, use the arrow member operator;

Alternatively, if PS is a pointer to a struct, then *ps is the value pointed to, that is, the structure itself, so it can be used (*PS). Name to access.

C + + Primer Puls Learning notes (ii)

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.