1. C + + Beginner
1.1 the first c + + program
#include <iostream> using namespace std; int main() { cout << "hello" << endl; system("pause"); return 0; }
result:
hello
1.2 notes
Single line and multi line notes
1.3 variables
Syntax: data type variable name = initial value;
Note: when creating a variable, C + + must give the variable an initial value, otherwise an error will be reported
1.4 constants
-
#Define macro constant: #define 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
Usually, the keyword const is added before the variable definition to modify the variable as a constant and cannot be modified
Example:
//1. Macro constant #define day 7 int main() { cout << "In a week " << day << " day" << endl; //day = 8; // An error is reported. Macro constants cannot be modified //2. const modifier variable const int month = 12; cout << "A total of in a year " << month << " Months" << endl; //month = 24; // An error is reported. Constants cannot be modified system("pause"); return 0; }
1.5 keywords
Tip: when naming variables or constants, do not use C + + keywords, otherwise ambiguity will occur.
asm | do | if | return | typedef |
---|---|---|---|---|
auto | double | inline | short | typeid |
bool | dynamic_cast | int | signed | typename |
break | else | long | sizeof | union |
case | enum | mutable | static | unsigned |
catch | explicit | namespace | static_cast | using |
char | export | new | struct | virtual |
class | extern | operator | switch | void |
const | false | private | template | volatile |
const_cast | float | protected | this | wchar_t |
continue | for | public | throw | while |
default | friend | register | true | |
delete | goto | reinterpret_cast | try |
1.6 identifier naming rules
Function: C + + has its own rules for naming identifiers (variables and constants)
- Identifier cannot be a keyword
- The identifier can only be composed of letters, numbers and underscores
- The first character must be a letter or underscore
- Letters in identifiers are case sensitive
Suggestion: when naming the identifier, try to achieve the effect of seeing the name and knowing the meaning, so as to facilitate reading by yourself and others
2 data type
C + + stipulates that when creating a variable or constant, the corresponding data type must be specified, otherwise memory cannot be allocated to the variable
2.1 integer
Function: integer variables represent integer data
There are several ways to represent integer types in C + +. The difference is that the memory space is different:
data type | Occupied space | Value range |
---|---|---|
Short (short integer) | 2 bytes | (-2^15 ~ 2^15-1) |
Int (integer) | 4 bytes | (-2^31 ~ 2^31-1) |
Long (long shaping) | 4 bytes for Windows, 4 bytes (32 bits) for Linux, 8 bytes (64 bits) | (-2^31 ~ 2^31-1) |
Long long | 8 bytes | (-2^63 ~ 2^63-1) |
2.2 sizeof keyword
Function: use sizeof keyword to count the memory size occupied by data type
Syntax: sizeof (data type / variable)
Example:
#include <iostream> using namespace std; int main() { cout << "short Memory space occupied by type: " << sizeof(short) << endl; cout << "int Memory space occupied by type: " << sizeof(int) << endl; cout << "long Memory space occupied by type: " << sizeof(long) << endl; cout << "long long Memory space occupied by type: " << sizeof(long long) << endl; system("pause"); return 0; }
result:
short Memory space occupied by type: 2 int Memory space occupied by type: 4 long Memory space occupied by type: 4 long long Memory space occupied by type: 8
2.3 real (floating point) (scientific counting method) (add an f after defining the float number)
Function: used to represent decimals
There are two types of floating point variables:
- Single precision float
- Double precision double
The difference between the two is that the range of significant numbers represented is different.
data type | Occupied space | Significant digit range |
---|---|---|
float | 4 bytes | 7 significant digits |
double | 8 bytes | 15 ~ 16 significant digits |
Example:
#include <iostream> using namespace std; int main() { float f1 = 3.1456756743f; double d1 = 3.1454545555; cout << f1 << endl; cout << d1 << endl; cout << "float sizeof = " << sizeof(f1) << endl; cout << "double sizeof = " << sizeof(d1) << endl; //Scientific counting method float f2 = 3e2; // 3 * 10 ^ 2 cout << "f2 = " << f2 << endl; float f3 = 3e-2; // 3 * 0.1 ^ 2 cout << "f3 = " << f3 << endl; system("pause"); return 0; }
Operation results:
3.14568 3.14545 float sizeof = 4 double sizeof = 8 f2 = 300 f3 = 0.03
The reason for adding an f after the float number is to reduce one-step conversion, because if it is not added, the system will recognize it as double
VS outputs up to six decimal places by default
2.4 character type
Function: character type variable is used to display a single character
Syntax: char ch = 'a';
Note 1: when displaying character variables, use single quotation marks to enclose the characters, not double quotation marks
Note 2: there can only be one character in a single quotation mark, not a string
- Character variables in C and C + + only occupy 1 byte.
- Character type variables do not store the character itself in memory, but put the corresponding ASCII code into the storage unit
Example:
#include <iostream> using namespace std; int main() { char ch = 'a'; cout << ch << endl; cout << sizeof(char) << endl; //ch = "abcde"; // Error, double quotation marks are not allowed //ch = 'abcde'; // Error, only one character can be referenced in a single quotation mark cout << (int)ch << endl; //View the ASCII code corresponding to character a ch = 97; //You can assign values to character variables directly in ASCII cout << ch << endl; system("pause"); return 0; }
Operation results:
a 1 97 a
2.5 escape characters
Function: used to represent some ASCII characters that cannot be displayed
At this stage, we often use escape characters: \ n \ \ t
Escape character | meaning | ASCII value (decimal) |
---|---|---|
\a | alert | 007 |
\b | Backspace (BS) to move 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 | Press enter (CR) to move 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 quotation mark (apostrophe) 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 hex |
Example:
#include <iostream> using namespace std; int main() { cout << "\\" << endl; cout << "\tHello" << endl; cout << "\n" << endl; system("pause"); return 0; }
result:
\ Hello
2.6 string type
Function: used to represent a string of characters
Two styles
-
C style string: char variable name [] = "string value"
Example:
int main() { char str1[] = "hello world"; cout << str1 << endl; system("pause"); return 0; }
Note: C-style strings should be enclosed in double quotes
- C + + style string: string variable name = "string value"
Example:
int main() { string str = "hello world"; cout << str << endl; system("pause"); return 0; }
Note: for C + + style strings, you need to add header files = = #include < string >==
2.7 boolean type bool
Role: Boolean data types represent true or false values
The bool type has only two values:
- True - true (essentially 1)
- False - false (essentially 0)
bool type takes up 1 byte
Example:
#include <iostream> using namespace std; int main() { bool flag = true; cout << flag << endl; // 1 flag = false; cout << flag << endl; // 0 cout << "size of bool = " << sizeof(bool) << endl; //1 system("pause"); return 0; }
2.8 data input (keyboard input cin)
Function: used to obtain data from the keyboard
Key words: cin
Syntax: CIN > > variable
Example:
#include <iostream> using namespace std; int main() { //Integer input int a = 0; cout << "Please enter an integer variable:" << endl; cin >> a; cout << a << endl; //Floating point input double d = 0; cout << "Please enter a floating point variable:" << endl; cin >> d; cout << d << endl; //Character input char ch = 0; cout << "Please enter a character variable:" << endl; cin >> ch; cout << ch << endl; //String input string str; cout << "Please enter a string variable:" << endl; cin >> str; cout << str << endl; //Boolean type input bool flag = true; cout << "Please enter a boolean variable:" << endl; cin >> flag; cout << flag << endl; system("pause"); return EXIT_SUCCESS; }
3 operator
Function: used to execute code operations
In this chapter, we mainly explain the following types of operators:
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 | Used to compare expressions and return a true or false value |
Logical operator | Used to return true or false values based on the value of an expression |
3.1 arithmetic operators
Function: used to process four operations
Arithmetic operators include the following symbols:
operator | term | Example | result |
---|---|---|---|
+ | Plus sign | +3 | 3 |
- | minus sign | -3 | -3 |
+ | plus | 10 + 5 | 15 |
- | reduce | 10 - 5 | 5 |
* | ride | 10 * 5 | 50 |
/ | except | 10 / 5 | 2 |
% | Mold taking (residual) | 10 % 3 | 1 |
++ | Pre increment | a=2; b=++a; | a=3; b=3; |
++ | Post increment | a=2; b=a++; | a=3; b=2; |
– | Pre decrement | a=2; b=–a; | a=1; b=1; |
– | Post decrement | a=2; b=a–; | a=1; b=2; |
Example 1:
#include <iostream> using namespace std; //add , subtract , multiply and divide int main() { int a1 = 10; int b1 = 3; cout << a1 + b1 << endl; //13 cout << a1 - b1 << endl; //7 cout << a1 * b1 << endl; //30 cout << a1 / b1 << endl; //3 the result of dividing two integers is still an integer int a2 = 10; int b2 = 20; cout << a2 / b2 << endl; //0 int a3 = 10; int b3 = 0; //cout << a3 / b3 << endl; // An error is reported. The divisor cannot be 0 //Two decimals can be divided double d1 = 0.5; double d2 = 0.25; cout << d1 / d2 << endl; //2 system("pause"); return 0; }
Example 2:
#include <iostream> using namespace std; //Take mold int main() { int a1 = 10; int b1 = 3; cout << 10 % 3 << endl; //1 int a2 = 10; int b2 = 20; cout << a2 % b2 << endl; //10 int a3 = 10; int b3 = 0; //cout << a3 % b3 << endl; // In modulo operation, the divisor cannot be 0 //Two decimals cannot be modulo double d1 = 3.14; double d2 = 1.1; //cout << d1 % d2 << endl; system("pause"); return 0; }
Example 3:
#include <iostream> using namespace std; //Increasing int main() { //Post increment int a = 10; a++; //Equivalent to a = a + 1 cout << a << endl; // 11 //Pre increment int b = 10; ++b; cout << b << endl; // 11 //difference //Pre incrementing first + + the variable, and then calculate the expression int a2 = 10; int b2 = ++a2 * 10; cout << b2 << endl; //110 //Post increment evaluates the expression first, and then the variable is incremented++ int a3 = 10; int b3 = a3++ * 10; cout << b3 << endl; //100 system("pause"); return 0; }
Conclusion: the pre increment is performed on the variable with + +, and then the expression is calculated. The post increment is the opposite
3.2 assignment operator
**Function: * * used to assign the value of an expression to a variable
The assignment operator includes the following symbols:
operator | term | Example | result |
---|---|---|---|
= | assignment | a=2; b=3; | a=2; b=3; |
+= | Plus equals | a=0; a+=2; | a=2; |
-= | Minus equals | a=5; a-=3; | a=2; |
*= | Multiply equal | a=2; a*=2; | a=4; |
/= | Division equals | a=4; a/=2; | a=2; |
%= | Modulo equal | a=3; a%2; | a=1; |
Example:
#include <iostream> using namespace std; int main() { //Assignment Operators // = int a = 10; a = 100; cout << "a = " << a << endl; //100 // += a = 10; a += 2; // a = a + 2; cout << "a = " << a << endl; //12 // -= a = 10; a -= 2; // a = a - 2 cout << "a = " << a << endl; //8 // *= a = 10; a *= 2; // a = a * 2 cout << "a = " << a << endl; //20 // /= a = 10; a /= 2; // a = a / 2; cout << "a = " << a << endl; //5 // %= a = 10; a %= 2; // a = a % 2; cout << "a = " << a << endl; //0 system("pause"); return 0; }
3.3 comparison operators
Function: used to compare expressions and return a true or false value
Comparison operators have the following symbols:
operator | term | Example | result |
---|---|---|---|
== | Equal to | 4 == 3 | 0 |
!= | Not equal to | 4 != 3 | 1 |
< | less than | 4 < 3 | 0 |
> | greater than | 4 > 3 | 1 |
<= | Less than or equal to | 4 <= 3 | 0 |
>= | Greater than or equal to | 4 >= 1 | 1 |
Example:
#include <iostream> using namespace std; int main() { int a = 10; int b = 20; cout << (a == b) << endl; // 0 cout << (a != b) << endl; // 1 cout << (a > b) << endl; // 0 cout << (a < b) << endl; // 1 cout << (a >= b) << endl; // 0 cout << (a <= b) << endl; // 1 system("pause"); return 0; }
Note: in the comparison operation of C and C + + languages, "true" is represented by the number "1", and "false" is represented by the number "0".
3.4 logical operators
**Function: * * used to return true or false values according to the value of the expression
Logical operators have the following symbols:
operator | term | Example | result |
---|---|---|---|
! | wrong | !a | If a is false, then! A is true; If a is true, then! A is false. |
&& | And | a && b | If both a and b are true, the result is true, otherwise it is false. |
|| | or | a || b | If one of a and b is true, the result is true. If both are false, the result is false. |
Example 1: logical non
#include <iostream> using namespace std; //Logical operator --- not int main() { int a = 10; cout << !a << endl; // 0 cout << !!a << endl; // 1 system("pause"); return 0; }
Summary: true becomes false, and false becomes true (as long as it is not 0, it is true)
Example 2: logic and
#include <iostream> using namespace std; //Logical operators --- and int main() { int a = 10; int b = 10; cout << (a && b) << endl;// 1 a = 10; b = 0; cout << (a && b) << endl;// 0 a = 0; b = 0; cout << (a && b) << endl;// 0 system("pause"); return 0; }
Summary: logic and operator summary: the same as true is true, and the rest is false
Example 3: logical or
#include <iostream> using namespace std; //Logical operator --- or int main() { int a = 10; int b = 10; cout << (a || b) << endl;// 1 a = 10; b = 0; cout << (a || b) << endl;// 1 a = 0; b = 0; cout << (a || b) << endl;// 0 system("pause"); return 0; }
4 program flow structure
C/C + + supports three basic program running structures: sequential structure, selection structure and loop structure
- Sequence structure: the program is executed in sequence without jump
- Select structure: perform corresponding functions selectively according to whether the conditions are met
- Loop structure: executes a piece of code multiple times according to whether the conditions are met
4.1 selection of structure
4.1.1 if statement
Function: execute statements that meet conditions
Three forms of if statements
-
Single line format if statement
-
Multiline if statement
-
Multi conditional if statement
-
Single line format if statement: if (condition) {statement executed when the condition is met}
Example:
#include <iostream> using namespace std; int main() { //Select structure - single line if statement //Enter a score. If the score is greater than 600, it will be regarded as entering a university and printed on the screen int score = 0; cout << "Please enter a score:" << endl; cin >> score; cout << "The score you entered is: " << score << endl; //if statement //Note: do not add a semicolon after the if judgment statement if (score > 600) { cout << "I was admitted to a university!!!" << endl; } system("pause"); return 0; }
Note: do not add a semicolon after the if conditional expression
- Multi line format if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet};
Example:
#include <iostream> using namespace std; int main() { int score = 0; cout << "Please enter the test score:" << endl; cin >> score; if (score > 600) { cout << "I was admitted to a university" << endl; } else { cout << "I failed to enter a university" << endl; } system("pause"); return 0; }
- Multi conditional if statement: if (condition 1) {condition 1 satisfies the executed statement} else if (condition 2) {condition 2 satisfies the executed statement}... Else {neither satisfies the executed statement}
Example:
#include <iostream> using namespace std; int main() { int score = 0; cout << "Please enter the test score:" << endl; cin >> score; if (score > 600) { cout << "I was admitted to a university" << endl; } else if (score > 500) { cout << "I was admitted to two universities" << endl; } else if (score > 400) { cout << "I was admitted to three universities" << endl; } else { cout << "I didn't go to college" << endl; } system("pause"); return 0; }
Nested if statements: if statements can be nested in if statements to achieve more accurate condition judgment
Case: omitted
4.1.2 ternary operator (omitted)
Function: realize simple judgment through ternary operator
Syntax: expression 1? Expression 2: expression 3
Explanation:
If the value of expression 1 is true, execute expression 2 and return the result of expression 2;
If the value of expression 1 is false, execute expression 3 and return the result of expression 3.
Summary: compared with the if statement, the advantage of the ternary operator is short and neat, but the disadvantage is that if nested, the structure is not clear
4.1.3 switch statement (omitted)
Function: execute multi conditional branch statements
Syntax:
switch(expression) { case Result 1: execute the statement;break; case Result 2: execute the statement;break; ... default:Execute statement;break; }
Note 1: the expression type in the switch statement can only be integer or character
Note 2: if there is no break in the case, the program will always execute downward
Conclusion: compared with if statements, for multi condition judgment, switch has clear structure and high execution efficiency. The disadvantage is that switch cannot judge the interval
4.2 circulation structure (omitted)
4.2.1 while loop statement
**Function: * * execute loop statements when loop conditions are met
Syntax: while (loop condition) {loop statement}
Explanation: as long as the result of the loop condition is true, the loop statement is executed
Note: when executing a loop statement, the program must provide an exit to jump out of the loop, otherwise an endless loop will occur
4.2.2 do... while loop statement
Function: execute loop statements when loop conditions are met
Syntax: do {loop statement} while (loop condition);
Note: the difference between do... While and while is that do... While will execute a loop statement first, and then judge the loop conditions
Summary: the difference between do... While and while loop is that do... While executes the loop statement once before judging the loop conditions
4.2.3 for loop statement (omitted)
Function: execute loop statements when loop conditions are met
Syntax: for (start expression; conditional expression; end loop body) {loop statement;}
Note: the expressions in the for loop should be separated by semicolons
Summary: while, do... While and for are loop statements commonly used in development. The for loop structure is relatively clear and commonly used
4.2.4 nested loop (omitted)
Function: nest another layer of loop in the loop body to solve some practical problems
For example, if we want to print the following pictures on the screen, we need to use nested loops
4.3 jump statement (omitted)
4.3.1 break statement
Function: used to jump out of the selection structure or loop structure
When to use break:
- It appears in the switch conditional statement to terminate the case and jump out of the switch
- Appears in a loop statement to jump out of the current loop statement
- Appears in a nested loop, jumping 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
Note: continue does not terminate the entire loop, but break will jump out of the loop
4.3.3 goto statement
Function: you can jump statements unconditionally
Syntax: goto tag;
Explanation: if the name of the tag exists, the goto statement will jump to the location of the tag
Note: goto statement is not recommended in the program to avoid confusion of program flow
5 array
5.1 general
An array is a collection containing data elements of the same type
Feature 1: each data element in the array is of the same data type
Feature 2: the array is composed of continuous memory locations
5.2 one dimensional array
5.2.1 definition method of one-dimensional array
There are three ways to define a one-dimensional 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...};
Example
#include <iostream> using namespace std; int main() { //Definition method 1 //Data type array name [number of elements]; int score[10]; //Assignment with subscript score[0] = 100; score[1] = 99; score[2] = 85; //Using subscript output cout << score[0] << endl; cout << score[1] << endl; cout << score[2] << endl; //The second definition method //Data type array name [number of elements] = {value 1, value 2, value 3...}; //If there are less than 10 data in {}, the remaining data shall be filled with 0 int score2[10] = { 100, 90,80,70,60,50,40,30,20,10 }; //Output one by one //cout << score2[0] << endl; //cout << score2[1] << endl; //One output is too cumbersome, so you can use loops to output for (int i = 0; i < 10; i++) { cout << score2[i] << endl; } //Definition mode 3 //Data type array name [] = {value 1, value 2, value 3...}; int score3[] = { 100,90,80,70,60,50,40,30,20,10 }; for (int i = 0; i < 10; i++) { cout << score3[i] << endl; } system("pause"); return 0; }
Summary 1: the naming convention of array name is consistent with that of variable name. Do not duplicate the name of variable
Summary 2: the index in the array starts from 0
5.2.2 one dimensional array name
Purpose of one-dimensional array name:
- You can count the length of the entire array in memory
- You can get the first address of the array in memory
Example:
#include <iostream> using namespace std; int main() { //Array name usage //1. You can get the memory space occupied by the entire array int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; cout << "The memory space occupied by the whole array is: " << sizeof(arr) << endl; //40 cout << "The memory space occupied by each element is: " << sizeof(arr[0]) << endl; //4 cout << "The number of elements of the array is: " << sizeof(arr) / sizeof(arr[0]) << endl; //10 //2. The first address of the array can be obtained through the array name (the decimal representation of the address is printed) cout << "The first address of the array is: " << (int)arr << endl; //13629676 cout << "The address of the first element in the array is: " << (int)&arr[0] << endl; //13629676 cout << "The address of the second element in the array is: " << (int)&arr[1] << endl; //13629680 //arr = 100; Error, array name is constant, so it cannot be assigned system("pause"); return 0; }
Note: the array name is a constant and cannot be assigned
Summary 1: print the array name directly, and you can view the first address of the memory occupied by the array
Summary 2: sizeof the array name can obtain the memory space occupied by the entire array
5.2.3 bubble sorting (omitted)
Function: the most commonly used sorting algorithm to sort the elements in the array
- Compare adjacent elements. If the first one is bigger than the second, exchange them.
- Do the same work for each pair of adjacent elements. After execution, find the first maximum value.
- Repeat the above steps for - 1 times each time until no comparison is needed
5.3 two dimensional array
A two-dimensional array is to add one more dimension to a one-dimensional array.
5.3.1 definition method of two-dimensional array
There are four ways to define a two-dimensional array:
- Data type array name [number of rows] [number of columns];
- Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}};
- Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4};
- Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4};
Suggestion: for the above four definitions, the second one is more intuitive to improve the readability of the code
Example:
#include <iostream> using namespace std; int main() { //Mode 1 //Array type array name [number of rows] [number of columns] int arr[2][3]; arr[0][0] = 1; arr[0][1] = 2; arr[0][2] = 3; arr[1][0] = 4; arr[1][1] = 5; arr[1][2] = 6; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr[i][j] << " "; } cout << endl; //endl is equivalent to newline\ n. It seems so } //Mode 2 //Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}}; int arr2[2][3] = { {1,2,3}, {4,5,6} }; //Mode 3 //Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4}; int arr3[2][3] = { 1,2,3,4,5,6 }; //Mode 4 //Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4}; int arr4[][3] = { 1,2,3,4,5,6 }; system("pause"); return 0; }
Operation results:
1 2 3 4 5 6
Summary: when defining a two-dimensional array, if data is initialized, the number of rows can be omitted
5.3.2 two dimensional array name
- View the memory space occupied by the two-dimensional array
- Get the first address of two-dimensional array
#include <iostream> using namespace std; int main() { //2D array name int arr[2][3] = { {1,2,3}, {4,5,6} }; cout << "2D array size: " << sizeof(arr) << endl; //24 cout << "One row size of two-dimensional array: " << sizeof(arr[0]) << endl; //12 cout << "2D array element size: " << sizeof(arr[0][0]) << endl; //4 cout << "Rows of 2D array: " << sizeof(arr) / sizeof(arr[0]) << endl; //2 cout << "Number of 2D array columns: " << sizeof(arr[0]) / sizeof(arr[0][0]) << endl; //3 //address cout << "First address of 2D array:" << arr << endl; //00CFFB88 cout << "Address of the first row of 2D array:" << arr[0] << endl; //00CFFB88 cout << "Address of the second row of 2D array:" << arr[1] << endl; //00CFFB94 (12 bytes from the above address) cout << "Address of the first element of 2D array:" << &arr[0][0] << endl; //00CFFB88 cout << "Address of the second element of 2D array:" << &arr[0][1] << endl; //00CFFB8C (4 bytes from the above address) system("pause"); return 0; }
Summary 1: the two-dimensional array name is the first address of the array
Summary 2: when sizeof a two-dimensional array name, you can obtain the memory space occupied by the entire two-dimensional array
5.3.3 application case of two-dimensional array (omitted)
6 function
6.1 general
Function: encapsulate a piece of frequently used code to reduce repeated code
A large program is generally divided into several program blocks, and each module realizes specific functions.
6.2 definition of function
The definition of a function generally consists of five steps:
1. Return value type
2. Function name
3. Parameter list
4. Function body statement
5. return expression
Syntax:
Return value type function name (parameter list) { Function body statement return expression }
- Return value type: a function can return a value. In function definition
- Function name: give the function a name
- Parameter list: the data passed in when using this function
- Function body statement: the code in curly braces and the statement to be executed in the function
- Return expression: linked to the return value type. After the function is executed, the corresponding data is returned
Example: define an addition function to add two numbers
//Function definition int add(int num1, int num2) { int sum = num1 + num2; return sum; }
6.3 function call
Function: use defined functions
Syntax: function name (parameter)
Example:
#include <iostream> using namespace std; //Function definition int add(int num1, int num2) //Num1 and num2 in the definition are called formal parameters, or formal parameters for short { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 10; //Call the add function int sum = add(a, b);//a and b at the time of calling are called actual parameters, which are referred to as actual parameters for short cout << "sum = " << sum << endl; //20 a = 100; b = 100; sum = add(a, b); cout << "sum = " << sum << endl; //200 system("pause"); return 0; }
Summary: the parentheses in the function definition are called formal parameters, and the parameters passed in during function call are called arguments
6.4 value transfer
- The so-called value passing means that the real parameter passes the value to the formal parameter when the function is called
- When a value is passed, if a formal parameter occurs, the argument is not affected
Example:
#include <iostream> using namespace std; void swap(int num1, int num2) { cout << "Before exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "After exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; //return ; When a function is declared, there is no need to return a value. You can not write return } int main() { int a = 10; int b = 20; swap(a, b); cout << "mian Medium a = " << a << endl; cout << "mian Medium b = " << b << endl; system("pause"); return 0; }
Operation results:
Before exchange: num1 = 10 num2 = 20 After exchange: num1 = 20 num2 = 10 mian Medium a = 10 mian Medium b = 20 Please press any key to continue. . .
6.5 common styles of functions
There are four common function styles
- No reference, no return
- There is no return
- Return without participation
- Participation and return
Example:
#include <iostream> using namespace std; //Common styles for functions //1. No reference, no return void test01() { //void a = 10; // No type. Cannot create variable because memory cannot be allocated cout << "this is test01" << endl; //test01(); function call } //2. There is no return void test02(int a) { cout << "this is test02" << endl; cout << "a = " << a << endl; } //3. Return without participation int test03() { cout << "this is test03 " << endl; return 10; } //4. Participation and return int test04(int a, int b) { cout << "this is test04 " << endl; int sum = a + b; return sum; }
6.6 function declaration
Function: tell the compiler the function name and how to call the function. The actual body of a function can be defined separately.
- A function can be declared multiple times, but a function can only be defined once
Example:
#include <iostream> using namespace std; //You can declare multiple times and define only once //statement int max(int a, int b); int max(int a, int b); //definition int max(int a, int b) { return a > b ? a : b; } int main() { int a = 100; int b = 200; cout << max(a, b) << endl; //200 system("pause"); return 0; }
6.7 function sub file preparation
Function: make the code structure clearer
Function sub file writing generally has four 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
Example:
//swap.h file #include<iostream> using namespace std; //A function declaration that implements the exchange of two numbers void swap(int a, int b);
//swap.cpp file #include "swap.h" void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }
//main function file #include "swap.h" int main() { int a = 100; int b = 200; swap(a, b); system("pause"); return 0; }
- Features: cpp file contains its own header file
- The header file contains built-in header files and declared functions
7 pointer
7.1 basic concept of pointer
Function of pointer: memory can be accessed indirectly through pointer
-
The memory number starts from 0 and is generally represented by hexadecimal digits
-
Pointer variables can be used to save addresses
7.2 definition and use of pointer variables
Pointer variable definition syntax: data type * variable name;
Example:
#include <iostream> using namespace std; int main() { //1. Definition of pointer int a = 10; //Define integer variable a //Pointer definition syntax: data type * variable name; int* p; //Pointer variable assignment p = &a; //The pointer points to the address of variable a cout << &a << endl; //Address of print data a # 00B3FECC cout << p << endl; //Print pointer variable p # 00B3FECC //2. Use of pointers //Memory pointed to by * operation pointer variable cout << "*p = " << *p << endl; //*p = 10 system("pause"); return 0; }
Difference between pointer variable and ordinary variable
- Ordinary variables store data, and pointer variables store addresses
- Pointer variables can operate the memory space pointed to by pointer variables through the "*" operator. This process is called dereference
Summary 1: we can get the address of the variable through the & symbol
Summary 2: use the pointer to record the address
Summary 3: dereference the pointer variable and operate the memory pointed to by the pointer
7.3 memory space occupied by pointer
Question: pointer is also a data type. How much memory does this data type occupy?
Example:
#include <iostream> using namespace std; int main() { int a = 10; int* p; p = &a; //The pointer points to the address of data a cout << *p << endl; //*Dereference ten cout << sizeof(p) << endl; //4 cout << sizeof(char*) << endl; //4 cout << sizeof(float*) << endl; //4 cout << sizeof(double*) << endl; //4 system("pause"); return 0; }
Summary: all pointer types are 4 bytes in 32-bit operating system (8 bytes in 64 bit operating system)
7.4 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
Example 1: null pointer
#include <iostream> using namespace std; int main() { //The pointer variable p points to the space with memory address number 0 int* p = NULL; //Error accessing null pointer //Memory numbers 0 ~ 255 are the memory occupied by the system and are not allowed to be accessed by users cout << *p << endl; //report errors system("pause"); return 0; }
Wild pointer: pointer variable points to illegal memory space
Example 2: field pointer
#include <iostream> using namespace std; int main() { //The pointer variable p points to the space with the memory address number 0x1100 int* p = (int*)0x1100; //Error in accessing field pointer cout << *p << endl; system("pause"); return 0; }
Conclusion: null pointer and wild pointer are not the space we apply for, so do not access.
7.5 const modifier pointer
const modifier pointer has three cases
- const modifier pointer - constant pointer
- const modifier constant - pointer constant
- const modifies both pointers and constants
Example:
#include <iostream> using namespace std; int main() { int a = 10; int b = 10; //const modifies the pointer. The pointer can be changed, and the value pointed to by the pointer cannot be changed const int* p1 = &a; p1 = &b; //correct //*p1 = 100; report errors //const is a constant. The pointer cannot be changed, and the value pointed to by the pointer can be changed int* const p2 = &a; //p2 = &b; // error *p2 = 100; //correct //const modifies both pointers and constants const int* const p3 = &a; //p3 = &b; // error //*p3 = 100; // error system("pause"); return 0; }
Tip: look at whether the pointer or constant is immediately followed on the right side of const. Whether the pointer is a constant pointer or a constant is a pointer constant
7.6 pointers and arrays
**Function: * * use pointer to access elements in array
Example:
#include <iostream> using namespace std; int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int* p = arr; //Pointer to array cout << "First element: " << arr[0] << endl; cout << "Pointer to access the first element: " << *p << endl; for (int i = 0; i < 10; i++) { //Traversing arrays with pointers cout << *p << endl; p++; } system("pause"); return 0; }
result:
First element: 1 Pointer to access the first element: 1 1 2 3 4 5 6 7 8 9 10
7.7 pointers and functions
**Function: * * use pointers as function parameters to modify the value of arguments
Example:
#include <iostream> using namespace std; //pass by value void swap1(int a, int b) { int temp = a; a = b; b = temp; } //Address delivery void swap2(int* p1, int* p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int a = 10; int b = 20; swap1(a, b); // Value passing does not change the argument cout << "a = " << a << endl; //10 cout << "b = " << b << endl; //20 swap2(&a, &b); //Address passing changes the arguments cout << "a = " << a << endl; //20 cout << "b = " << b << endl; //10 system("pause"); return 0; }
Summary: if you don't want to modify the argument, pass it by value. If you want to modify the argument, pass it by address
7.8 pointer, array and function (omitted)
**Case description: * * encapsulates a function that uses bubble sorting to sort integer arrays in ascending order
For example, array: int arr [10] = {4,3,6,9,1,2,10,8,7,5};
Summary: when an array name is passed into a function as an argument, it is degenerated into a pointer to the first element
8 structure
8.1 basic concept of structure
Structures are user-defined data types, allowing users to store different data types
8.2 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...}
- Create variables as you define the structure
Example:
#include <iostream> using namespace std; //Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction }stu3; //Structure variable creation method 3 int main() { //Structure variable creation method 1 struct student stu1; //The struct keyword can be omitted stu1.name = "Zhang San"; stu1.age = 18; stu1.score = 100; cout << "full name:" << stu1.name << " Age:" << stu1.age << " fraction:" << stu1.score << endl; //Structure variable creation method 2 struct student stu2 = { "Li Si",19,60 }; cout << "full name:" << stu2.name << " Age:" << stu2.age << " fraction:" << stu2.score << endl; stu3.name = "Wang Wu"; stu3.age = 18; stu3.score = 80; cout << "full name:" << stu3.name << " Age:" << stu3.age << " fraction:" << stu3.score << endl; system("pause"); return 0; }
Operation results:
Name: Zhang San age: 18 score: 100 Name: Li Si age: 19 score: 60 Name: Wang Wu age: 18 score: 80
Summary 1: the keyword used to define a structure is struct, which cannot be omitted
Summary 2: when creating structural variables, the keyword struct can be omitted
Summary 3: struct variables access members using the operator '.'
8.3 structure array
Function: put the custom structure into the array for easy maintenance
Syntax: struct structure name array name [number of elements] = {{}, {},... {}}
Example:
#include <iostream> using namespace std; //Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction }; int main() { //Structure array struct student arr[3] = { {"Zhang San",18,80 }, {"Li Si",19,60 }, {"Wang Wu",20,70 } }; for (int i = 0; i < 3; i++) { cout << "full name:" << arr[i].name << " Age:" << arr[i].age << " fraction:" << arr[i].score << endl; } system("pause"); return 0; }
Operation results:
Name: Zhang San age: 18 score: 80 Name: Li Si age: 19 score: 60 Name: Wang Wu age: 20 score: 70
8.4 structure pointer
**Function: * * access members in a structure through a pointer
- Using the operator - > you can access structure properties through the structure pointer
Example:
#include <iostream> using namespace std; //Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction }; int main() { struct student stu = { "Zhang San",18,100, }; struct student* p = &stu; p->score = 80; //Members can be accessed through the pointer - > operator cout << "full name:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl; system("pause"); return 0; }
Operation results:
Name: Zhang San age: 18 score: 80
Summary: structure pointers can access members in a structure through the - > operator
8.5 nested structures
Action: a member in a structure can be another structure
For example, each teacher tutors a student. In the structure of a teacher, record the structure of a student
Example:
#include <iostream> using namespace std; //Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //Definition of teacher structure struct teacher { //Member list int id; //Employee number string name; //Teacher name int age; //Teacher age struct student stu; //Substructure student }; int main() { struct teacher t1; t1.id = 10000; t1.name = "Lao Wang"; t1.age = 40; t1.stu.name = "Zhang San"; t1.stu.age = 18; t1.stu.score = 100; cout << "Teacher employee No.: " << t1.id << " full name: " << t1.name << " Age: " << t1.age << endl; cout << "Name of trainee: " << t1.stu.name << " Age:" << t1.stu.age << " Test score: " << t1.stu.score << endl; system("pause"); return 0; }
Teacher staff No.: 10000 Name: Lao Wang age: 40 Name of Tutor: Zhang San age: 18 test score: 100
**Summary: * * in a structure, another structure can be defined as a member to solve practical problems
8.6 function parameters of struct (comparison between passed struct and passed struct pointer)
Function: pass structure as parameter to function
There are two delivery methods:
- pass by value
- Address delivery
Example:
#include <iostream> using namespace std; //Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //pass by value void printStudent(student stu) { stu.age = 28; cout << "Name in subfunction:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; } //Address delivery void printStudent2(student* stu) { stu->age = 28; cout << "Name in subfunction:" << stu->name << " Age: " << stu->age << " fraction:" << stu->score << endl; } int main() { student stu = { "Zhang San",18,100 }; //pass by value printStudent(stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; cout << endl; //Address delivery printStudent2(&stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; system("pause"); return 0; }
Name in subfunction: Zhang San age: 28 score: 100 Name in main function: Zhang San age: 18 score: 100 Name in subfunction: Zhang San age: 28 score: 100 Name in main function: Zhang San age: 28 score: 100
Summary: if you do not want to modify the data in the main function, pass it by value, otherwise pass it by address
8.7 const usage scenario in structure
Function: use const to prevent misoperation
Example:
#include <iostream> using namespace std; //Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //const usage scenario void printStudent(const student* stu) //Add const to prevent misoperation in function body { //stu->age = 100; // The operation failed because of the const modifier cout << "full name:" << stu->name << " Age:" << stu->age << " fraction:" << stu->score << endl; } int main() { student stu = { "Zhang San",18,100 }; printStudent(&stu); system("pause"); return 0; }
8.8 structure case (note that when the array name is passed as a function parameter, the first element address is passed) (set the random number seeds srand and rand())
8.8.1 case 1
Case description:
The school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows
Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members
Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions
Finally, print out the teacher data and the student data brought by the teacher.
Example:
#include <iostream> using namespace std; struct Student { string name; int score; }; struct Teacher { string name; Student sArray[5]; }; void allocateSpace(Teacher tArray[], int len) { string tName = "teacher"; string sName = "student"; string nameSeed = "ABCDE"; for (int i = 0; i < len; i++) { tArray[i].name = tName + nameSeed[i]; for (int j = 0; j < 5; j++) { tArray[i].sArray[j].name = sName + nameSeed[j]; tArray[i].sArray[j].score = rand() % 61 + 40; } } } void printTeachers(Teacher tArray[], int len) { for (int i = 0; i < len; i++) { cout << tArray[i].name << endl; for (int j = 0; j < 5; j++) { cout << "\t full name:" << tArray[i].sArray[j].name << " fraction:" << tArray[i].sArray[j].score << endl; } } } int main() { srand((unsigned int)time(NULL)); //Random number seed header file #include < CTime > Teacher tArray[3]; //Teacher array int len = sizeof(tArray) / sizeof(Teacher); allocateSpace(tArray, len); //Create data printTeachers(tArray, len); //print data system("pause"); return 0; }
Operation results:
teacher A Name: Student A Score: 75 Name: Student B Score: 58 Name: Student C Score: 79 Name: Student D Score: 44 Name: Student E Score: 56 teacher B Name: Student A Score: 46 Name: Student B Score: 42 Name: Student C Score: 75 Name: Student D Score: 97 Name: Student E Score: 40 teacher C Name: Student A Score: 62 Name: Student B Score: 63 Name: Student C Score: 42 Name: Student D Score: 92 Name: Student E Score: 99