1. Getting to know C++
1.1 first C + + program
To create a new project, select Create an empty project for C + +:
Select project name and location:
To add a C + + file to the source file:
# include <iostream> using namespace std; int main() { // nowrap cout << "hello world" ; // Line feed, line feed with < < endl cout << "hello world" << endl; // So this is a simple line feed cout << endl; system("pause"); return 0; }
1.2 notes
# include <iostream> using namespace std; // 1. Single line notes /* multiline comment */ int main() { cout << "hello world" << endl; system("pause"); return 0; }
1.3 variables and constants
Is to name a designated space to facilitate the operation of this space.
Create variable: data type variable name = variable initial value;
Constant: records data that cannot be changed in a program
How to define constants:
- #define macro constant: # constant name constant value
- It is usually defined above the file to represent a constant.
- Const modified variable: const data type constant name = constant value
- The keyword const is usually added before the variable definition to modify the variable as a constant and cannot be modified.
# include <iostream> using namespace std; # define Weekday 7 int main() { const int a = 10; cout << "a = " << a <<endl; cout << "A week:" << Weekday << "day" << endl; system("pause"); return 0; }
1.4 keywords
Reserved words in C + + cannot be used when defining variables or constants
1.5 identifier naming rules
- Identifier cannot be a keyword
- The identifier can only be composed of letters, numbers and underscores
- The first character must be a letter or an underscore
- Letters in identifiers are case sensitive
- It is better to know its meaning through the identifier
2. Data type
The meaning of data type: allocate an appropriate memory space for variables.
Scientific counting method:
- 3e2: 3 * 102
- 3e-2:3 * 0.12
2.1 shaping
data type | Occupied space | Value range |
---|---|---|
Short (short integer) | 2 bytes | (-215 ~ 215-1 ) |
int (integer) | 4 bytes | (-231 ~ 231-1 ) |
Long (long shaping) | 4 bytes for Windows, 4 bytes (32 bits) for Linux, 8 bytes (64 bits) | (-231 ~ 231-1 ) |
long long | 8 bytes | (-263 ~ 263-1 ) |
2.2sizeof keyword
Memory occupied by statistics type
2.3 real (floating point)
data type | Occupied space | Significant digit range |
---|---|---|
float (single precision) | 4 bytes | 7 significant digits |
Double (double) | 8 bytes | 15 ~ 16 significant digits |
2.4 character type
Used to represent a single letter
- Character variables occupy only one byte.
- Character type variables do not store the character itself in memory, but put the corresponding ASCII code in the storage unit.
# include <iostream> using namespace std; int main() { char ch = 'a'; cout << ch << endl; cout << sizeof(ch) << endl; /* a 1 */ // ASCII encoding corresponding to character type variable // a 97 // A 65 cout << (int)ch << endl; // 97 // You can assign values to character variables through ASCII char ch2 = 98; cout << ch2 << endl; // b system("pause"); return 0; }
Common errors:
- Use double quotation marks: char ch = "a";
- Put multiple characters in single quotation marks: char ch = 'asd';
ASCII code table
- ASCII non printing control characters: the numbers 0 ~ 31 on the ASCII table are assigned to the control characters, which are used to control peripheral devices.
- ASCII printed characters: the numbers 32 to 126 are assigned to characters that can be found on the keyboard and appear when viewing or printing a document.
ASCII value | Control character | ASCII value | character | ASCII value | character | ASCII value | character |
---|---|---|---|---|---|---|---|
0 | NUT | 32 | (space) | 64 | @ | 96 | ` |
1 | SOH | 33 | ! | 65 | A | 97 | a |
2 | STX | 34 | " | 66 | B | 98 | b |
3 | ETX | 35 | # | 67 | C | 99 | c |
4 | EOT | 36 | $ | 68 | D | 100 | d |
5 | ENQ | 37 | % | 69 | E | 101 | e |
6 | ACK | 38 | & | 70 | F | 102 | f |
7 | BEL | 39 | , | 71 | G | 103 | g |
8 | BS | 40 | ( | 72 | H | 104 | h |
9 | HT | 41 | ) | 73 | I | 105 | i |
10 | LF | 42 | * | 74 | J | 106 | j |
11 | VT | 43 | + | 75 | K | 107 | k |
12 | FF | 44 | , | 76 | L | 108 | l |
13 | CR | 45 | - | 77 | M | 109 | m |
14 | SO | 46 | . | 78 | N | 110 | n |
15 | SI | 47 | / | 79 | O | 111 | o |
16 | DLE | 48 | 0 | 80 | P | 112 | p |
17 | DC1 | 49 | 1 | 81 | Q | 113 | q |
18 | DC2 | 50 | 2 | 82 | R | 114 | r |
19 | DC3 | 51 | 3 | 83 | S | 115 | s |
20 | DC4 | 52 | 4 | 84 | T | 116 | t |
21 | NAK | 53 | 5 | 85 | U | 117 | u |
22 | SYN | 54 | 6 | 86 | V | 118 | v |
23 | TB | 55 | 7 | 87 | W | 119 | w |
24 | CAN | 56 | 8 | 88 | X | 120 | x |
25 | EM | 57 | 9 | 89 | Y | 121 | y |
26 | SUB | 58 | : | 90 | Z | 122 | z |
27 | ESC | 59 | ; | 91 | [ | 123 | { |
28 | FS | 60 | < | 92 | \ | 124 | | |
29 | GS | 61 | = | 93 | ] | 125 | } |
30 | RS | 62 | > | 94 | ^ | 126 | ~ |
31 | US | 63 | ? | 95 | - | 127 | DEL |
2.5 escape characters
Function: used to display some ASCII characters that cannot be expressed directly.
Escape character | meaning | ASCII value (decimal) |
---|---|---|
\a | alert | 007 |
\b | Backspace (BS) moves the current position to the previous column | 008 |
\f | Page feed (FF) moves the current position to the beginning of the next page | 012 |
\n | Line feed (LF) moves the current position to the beginning of the next line | 010 |
\r | Enter (CR) moves the current position to the beginning of the line | 013 |
\t | Horizontal tabulation (HT) (skip to next TAB position) | 009 |
\v | Vertical tabulation (VT) | 011 |
\\ | Represents a backslash character '\' | 092 |
\' | Represents a single quote character | 039 |
\" | Represents a double quote character | 034 |
\? | Represents a question mark | 063 |
\0 | Number 0 | 000 |
\ddd | Octal escape character, d range 0 ~ 7 | 3-bit octal |
\xhh | Hexadecimal escape character, h range 09, af, A~F | 3-bit octal |
2.6 string type
Represents a string of characters
- Array style string: char variable name [] = "string value";
- C + + style string: string variable name = "string value"; (a header file is required: # include < string >)
2.7 boolean type bool
Represents true or false values
There are only two values:
- True: stands for true
- False: false
They are essentially 0 or 1, and the bool type takes up one byte.
2.8 data input
Get data from keyboard
Key words: cin
# include <iostream> using namespace std; int main() { // 1. Shaping int a = 0; cout << "Please give integer variable a assignment:" << endl; cin >> a; cout << "Integer variable a = " << a << endl; // 2. Floating point type float f = 3.14f; cout << "Please give floating point variables f assignment:" << endl; cin >> f; cout << "Integer variable f = " << f << endl; // 3. Character type char ch = 'a'; cout << "Please give a character variable ch assignment:" << endl; cin >> ch; cout << "Integer variable ch = " << ch << endl; system("pause"); return 0; }
3. Operator
Operator type | effect |
---|---|
Arithmetic operator | Used to process four operations |
Assignment Operators | Used to assign the value of an expression to a variable |
Comparison operator | Comparison for expressions |
Logical operator | Used to return true or false values based on the value of an expression |
3.1 arithmetic operators
operator | term | explain |
---|---|---|
+ | Plus sign | Symbol |
- | minus sign | Symbol |
+ | plus | |
- | reduce | |
* | ride | |
/ | except | |
% | Mold taking (residual) | Remainder (two decimals cannot be modulo) |
++ | Pre increment | Add one first and then the operation of the expression |
++ | Post increment | First the operation of the expression, and then add one |
– | Pre decrement | ditto |
– | Post decrement | ditto |
3.2 assignment operator
operator | term |
---|---|
= | assignment |
+= | Plus equals |
-= | Minus equals |
*= | Multiply equal |
/= | Division equals |
%= | Modulo equal |
3.3 comparison operators
operator | term |
---|---|
== | Wait for |
!= | Not equal to |
> | greater than |
< | less than |
>= | Greater than or equal to |
<= | Less than or equal to |
3.4 logical operators
operator | term |
---|---|
! | wrong |
|| | or |
&& | And |
4. Procedure flow structure
4.1 selection of structure
4.1.1 if statement
# include <iostream> using namespace std; int main() { int score = 0; cout << "Please enter your score:" << endl; cin >> score; // Single line if statement: if (condition) {statement executed when the condition is met} if(score>=60){ cout << "You passed" << endl; } // Multiline if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet} if(score>=60){ cout << "You passed" << endl; }else{ cout << "You failed" << endl; } // Multi conditional if statements: if (condition 1) {statements executed when condition 1 meets} else if (condition 2) {statements executed when condition 2 meets}... Else {statements executed when all conditions are not met} if(score>=90) { cout << "Excellent results" << endl; } else if(score>=60) { cout << "Pass the grade" << endl; } else { cout << "Fail" << endl; } // Nested if statements: if (condition 1) {if (condition 2) {if (condition 3) {} if(score>=60) { cout << "Pass the grade" << endl; if(score>=90) { cout << "Excellent results" << endl; } } else { cout << "Fail" << endl; } system("pause"); return 0; }
4.1.2 ternary operator
# include <iostream> using namespace std; int main() { // Expression 1? Expression 2: expression 3; // If expression 1 is true, expression 2 is executed, otherwise expression 3 is executed // Maximum number of outputs int a = 10; int b = 20; int max = a>b?a:b; cout << max << endl; system("pause"); return 0; }
4.1.3 switch statement
# include <iostream> using namespace std; int main() { // Multi conditional branch statement /* switch((expression) { case Result 1: Execute statements; break; case Result 2: Execute statements; break; case Result 3: Execute statements; break; case Result 4: Execute statements; break; ... default:Execute statements; break; } */ system("pause"); return 0; }
4.2 circulation structure
Random number generated by the system:
//Time system time header file # include <ctime> // Add random number seeds and generate random numbers using the current system time to prevent the random numbers from being the same every time. srand((unsigned int)time(NULL)); rand() % 100 + 1; // rand() generates a random number // Rand()% 100 generates random numbers from 0 to 99 // Rand()% 100 + 1 generates random numbers from 1 to 100
4.2.1 while loop statement
# include <iostream> using namespace std; int main() { /* while(Cycle conditions) { Circular statement } */ system("pause"); return 0; }
4.2.2do... while loop statement
# include <iostream> using namespace std; int main() { /* First execute the loop statement once, and then judge the loop. do { Loop statement; } while(Cycle conditions); */ system("pause"); return 0; }
4.2.3 for loop statement
# include <iostream> using namespace std; int main() { /* for(Start expression; Conditional expression; End loop body) { Loop statement; } */ system("pause"); return 0; }
4.2.4 nested loops
# include <iostream> using namespace std; int main() { /* for(Start expression; Conditional expression; End loop body) { Loop statement; for(Start expression; Conditional expression; End loop body) { Loop statement; } } */ system("pause"); return 0; }
4.3 jump statement
4.3.1 break statement
Jump out of selection structure or loop structure
- In the switch statement, the function is to terminate the case and jump out of the switch
- In the circular statement, the function is to jump out of the current circular statement
- Appears in a nested loop to jump out of the nearest inner loop statement
4.3.2 continue statement
Function: in a loop statement, skip the remaining unexecuted statements in this loop and continue to execute the next loop.
4.3.3 goto statement
Not recommended
# include <iostream> using namespace std; int main() { /* Function: unconditional jump Usage: goto tag; When the goto statement is executed, if the name of the tag exists, it will jump to the location of the tag. */ cout << "first" << endl; goto FLAG; cout << "the second" << endl; cout << "Third" << endl; FLAG: cout << "Fourth" << endl; cout << "Fifth" << endl; cout << "Sixth" << endl; system("pause"); return 0; }
5. Array
An array is a collection of the same elements
characteristic:
- Each data element in the array is of the same data type.
- An array consists of contiguous memory locations.
5.1 one dimensional array
Definition of array
- Data type array name [array length];
- Data type array name [array length] = {value 1, value 2...};
- Data type array name [] = {value 1, value 2...};
Purpose of array name
- You can count the length of the entire array in memory.
- Sizeof (array name);
- You can get the first address of the array in memory.
- (int) array name: This outputs the decimal first address.
- Array name: This outputs the first hexadecimal address.
- (int) & array name [0]: the address of the first element in the array. The address of the first element is the first address of the array.
- The array name is a constant and cannot be assigned.
5.2 two dimensional array
Array definition (the second is recommended)
- Data type array name [number of rows] [number of columns];
- Data type array name [number of rows] [number of columns] = {value 11, value 12...}, {value 21, value 22...}...};
- Data type array name [number of rows] [number of columns] = {value 1, value 2, value 3, value 4, value 5...};
- Data type array name [] [number of columns] = {value 1, value 2, value 3, value 4, value 5...};
Purpose of array name
- View the memory space occupied by the two-dimensional array
- Get the first address of two-dimensional array
6. Function
Function: encapsulate a piece of frequently used code to reduce code duplication. Large programs will be divided into several program blocks, and each module will realize specific functions.
6.1 definition of function
/* Syntax: Return value type function name (parameter list) { Function body statement return expression } */
6.2 function call
# include <iostream> using namespace std; // Function declaration: if the function to be called is defined after the function to be called, you need to declare the function. int add(int num1,int num2); int main() { int a = 1; int b = 2; // When calling a function, the passed a and b have actual values, and they become arguments. int c = add(a, b); cout << "c=" << c << endl; system("pause"); return 0; } // When defining, num1 and num2 have no real data. At this time, it is a formal parameter. int add(int num1, int num2) { int sum = num1 + num2; return sum; }
Note: any change in the formal parameter in the function during value transfer will not affect the actual parameter value.
6.3 function sub file preparation
Function: make the code structure clearer
Steps:
- Create a header file with the suffix. h
- Create a source file with the suffix. cpp
- Write the declaration of the function in the header file
- Write the definition of the function in the source file
// swap.h # include <iostream> using namespace std; // Declaration of function void swap(int a, int b);
// swap.cpp # include "swap.h" void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }
// The main function is called the source file # include <iostream> # include "swap.h" // It is written by yourself to use double quotation marks, and it is written by others to use angle brackets. using namespace std; int main() { int a = 1; int b = 2; swap( a, b); system("pause"); return 0; }
7. Pointer
Function: indirect access to memory through pointer.
7.1 definition and use of pointer
# include <iostream> using namespace std; int main() { // Define pointer int a = 10; // Syntax of pointer definition: data type * pointer variable name; int * p; //Pointer variable records the address of variable a p = &a; // Use pointer cout << "a Your address is:" << &a << endl; cout << "a Your address is:" << p << endl; // You can find the memory stored value pointed to by the pointer by dereference. cout << "Pointer p Points to the value stored in the memory space" << *p << endl; // You can change the value stored in the specified memory space in this way *p = 100; cout << "a = " << a << endl; cout << "*P = " << *p << endl; system("pause"); return 0; }
In the 32-bit operating system, the memory space occupied by pointers is fixed at 4 bytes, and in the 64 bit operating system, it is 8 bytes (whether int, double... All types of pointers are the same)
7.2 null pointer and wild pointer
Null pointer: pointer variable points to the space numbered 0 in memory.
Purpose: initialize pointer variables.
Note: the memory pointed to by the null pointer is inaccessible.
Wild pointer: pointer variable points to illegal memory space. Avoid wild pointer in the program.
// Define null pointer int *p = NULL; // Define field pointer int *p = (int *)0x1234; // 0x1234 this memory space is not owned by itself and has no permission to operate it.
7.3 const modifier pointer
const modifies pointers in three ways:
- const modifier pointer: constant pointer.
- const modifier constant: pointer constant.
- const modifies both pointers and constants.
/* const pointer Features: the pointer can be modified, but the value pointed to by the pointer cannot be modified. */ const int * p = &a; /* constant pointer Features: the pointer cannot be modified, and the value pointed by the pointer can be modified. */ int * const p = &a; /* const That is, it modifies both pointers and constants Features: the pointing of the pointer cannot be modified, and the value pointed by the pointer cannot be modified. */ const int * const p = &a;
7.4 joint use of pointer, array and function
# include <iostream> using namespace std; void swap(int * p1, int * p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Using pointers to access elements in an array int *p = arr; // arr is the first address of the array cout << "Accessing the first element with a pointer:" << *p << endl; p++; // Let the pointer back 4 bytes, and the pointer points to the second element. cout << "Accessing the second element with a pointer:" << *p << endl; cout << "Traverse the array with a pointer:" << endl; // Using pointers to facilitate arrays int * p2 = arr; for (int i = 0; i < 10; i++) { cout << *p << endl; p++; } //Address passing will change the argument value int a = 10; int b = 20; swap(&a, &b); cout << "After exchange a:" << a << endl; cout << "After exchange b:" << b << endl; system("pause"); return 0; }
// Encapsulates a function that uses bubble sorting to sort an integer array in ascending order # include <iostream> using namespace std; void bubbleSort(int * arr, int len) { for(int i = 0; i < len - 1; i++) { for(int j = 0; j < len - i - 1; j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main() { int arr[10] = {4, 3, 6, 9, 1, 2, 7, 5, 8}; bubbleSort(arr, 9); system("pause"); return 0; }
8. Structure
Structures are user-defined data types, allowing users to store different data types
8.1 definition and use of structure
Syntax: struct structure name {structure member list};
There are three ways to create variables through structures:
- struct structure name variable name
- struct structure name variable name = {member 1 value, member 2 value...}
- When you define a structure, you create variables
#include <iostream> using namespace std; #include <string> struct Student { string name; int age; int score; }s3; // Create variables when defining structures int main() { // The struct keyword can be omitted when creating variables struct Student s1; s1.name = "Zhang San"; s1.age = 15; s1.score = 90; struct Student s2 = {"Li Si", 16, 89}; s3.name = "Wang Wu"; s3.age = 16; s3.score = 91; system("pause"); return 0; }
Structure array: struct structure name array name [number of elements] = {}, {}, {},...}
8.2 structure pointer
Accessing members in a structure through a pointer
- Using the operator - > you can access structure properties through the structure pointer
#include <iostream> using namespace std; #include <string> struct Student { string name; int age; int score; }; int main() { // Create student structure variable Student s = {"Zhang San", 18, 100}; // Pointer to structure variable Student *p = &s; // Accessing data in structure variables through pointers cout << "full name:" << p->name << "Age:" << p->age << "fraction:" << p->score << endl; system("pause"); return 0; }
8.3 structure nested structure
#include <iostream> using namespace std; #include <string> struct Student { string name; int age; int score; }; struct Teacher { int id; string name; int age; struct Student stu; }; int main() { // Create teacher Teacher t; t.id = 100; t.name = "Lao Wang"; t.age = 50; t.stu.name = "Xiao Wang"; t.stu.age = 18; t.stu.score = 89; cout << "Teacher's name:" << t.name << "Teacher's age:" << t.age << "Teacher's number:" << t.id << << "Teacher's Student Name:" << t.stu.name << "Age of teacher's students:" << t.stu.age << "Teacher's student performance:" << t.stu.score << endl; system("pause"); return 0; }
8.4 structure as function parameter
- pass by value
- Address delivery
As with ordinary parameters, value passing only passes values, and changing formal parameters does not change arguments.
8.5 const usage scenario in structure
Function: prevent misoperation
#include <iostream> using namespace std; #include <string> struct Student { string name; int age; int score; }; void printStudents(const Student * s) { //S - > age = 100; / / after using const modification, an error will be reported once the operation is modified, which can prevent misoperation. // Here, if you don't use address transfer and directly use value transfer, even if you modify it, it won't change the value of the most original data. Why not? // Because if you use value passing, you need to re open up an address space. If the amount of data passed is too large, it will consume a lot of space. If you use address passing, you only need to open up a pointer space. cout << "Student Name:" << s->name << " Age:" << s->age << " fraction:" << s->score << endl; } int main() { // Create student structure variable Student s = {"Zhang San", 18, 100}; printStudents(s); cout << "full name:" << s.name << "Age:" << s.age << "fraction:" << s.score << endl; system("pause"); return 0; }