Basic review of C + + introduction

Keywords: C C++

sizeof keyword

The sizeof keyword can be used to count the memory size occupied by the data type
Syntax: sizeof (data type / variable)
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;

}

C/C + + supports three basic program running structures: sequential structure, selection structure and loop structure

ternary operator

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.
int main() {

int a = 10;
int b = 20;
int c = 0;

c = a > b ? a : b;
cout << "c = " << c << endl;

//The ternary operator in C + + returns variables and can continue to assign values

(a > b ? a : b) = 100;

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

system("pause");

return 0;

}

switch Statements

Switch (expression)
​{​
case result 1: execute the statement; break; ​
case result 2: execute the statement; break; ​
...​
default: execute statement; break;
​}​
Note: the expression type in the switch statement can only be integer or character type;
If there is no break in the case, the program will always execute downward

for loop:

For (start expression; conditional expression; end loop body) {loop statement;}

continue

**Function: * * in a loop statement, skip the remaining unexecuted statements in this loop and continue to execute the next loop

int main() {

for (int i = 0; i < 100; i++)
{
	if (i % 2 == 0)
	{
		continue;
	}
	cout << i << endl;
}

system("pause");

return 0;

}

When i is 2, the modulus is 0, if is judged to be true, execute continue, jump out of the unexecuted statement in the loop (cout < < i < < endl;), and execute the operation of i + +

Bubble sorting

  1. Compare adjacent elements. If the first is larger than the second, swap them.

  2. Do the same work for each pair of adjacent elements. After execution, find the first maximum value.

  3. Repeat the above steps for - 1 times each time until no comparison is needed
    Example: sort the array {4,2,8,0,5,7,1,3,9} in ascending order
    int main() {

    int arr[9] = { 4,2,8,0,5,7,1,3,9 };

    for (int i = 0; i < 9 - 1; i++)
    {
    for (int j = 0; j < 9 - 1 - i; j++)
    {
    if (arr[j] > arr[j + 1])
    {
    int temp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = temp;
    }
    }
    }

    for (int i = 0; i < 9; i++)
    {
    cout << arr[i] << endl;
    }

    system("pause");

    return 0;
    }

//Bubble sorting
void bubbleSort(hero arr[] , int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (arr[j].age > arr[j + 1].age)
			{
				hero temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

Array (one dimensional array)

There are three ways to define a one-dimensional array:

  1. Data type array name [array length];
  2. Data type array name [array length] = {value 1, value 2...};
  3. Data type array name [] = {value 1, value 2...};

Array (2D array)

There are four ways to define a two-dimensional array:

  1. Data type array name [number of rows] [number of columns];
  2. Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}};
  3. Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4};
  4. Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4};

Summary: when defining a two-dimensional array, if data is initialized, the number of rows can be omitted

function

The definition of a function generally consists of five steps:

1. Return value type: a function can return a value. In the function definition

2. Function name: give the function a name

3. Parameter table column: the data passed in when using this function

4. Function body statement: the code in curly braces and the statement to be executed in the function

5. Return expression: linked to the return value type. After the function is executed, the corresponding data is returned

Syntax:

Return value type function name (parameter list)
{

       Function body statement

       return expression

}

**Example: * * define an addition function to add two numbers

 //Function definition
int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;
}

function call

Syntax: ` function name (parameter)
//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;

	a = 100;
	b = 100;

	sum = add(a, b);
	cout << "sum = " << sum << endl;

	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

pass by value

  • 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
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, you do not need to return a value, so 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;
}


Summary: formal parameters cannot modify arguments when passing values

Function declaration

Tells the compiler the name of the function and how to call it. The actual body of the function can be defined separately.

  • A function can be declared multiple times, but a function can only be defined once

Function sub file writing

**Function: * * make the code structure clearer

Function sub file writing generally has four steps

  1. Create a header file with the suffix. h
  2. Create a source file with the suffix. cpp
  3. Write the declaration of the function in the header file
  4. 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;
}

Pointer

Function of pointer: memory can be accessed indirectly through pointer
Pointer variable definition syntax: data type * variable name;

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
	cout << p << endl;  //Print pointer variable p

	//2. Use of pointers
	//Memory pointed to by * operation pointer variable
	cout << "*p = " << *p << endl;

	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

Null pointer and wild pointer

Null pointer: pointer variable points to the space numbered 0 in memory

**Purpose: * * initialize pointer variable

**Note: * * the memory pointed to by the null pointer is inaccessible

Wild pointer: pointer variable points to illegal memory space

const modifier pointer

const modifier pointer has three cases

  1. Const modifies pointer constant pointer: const modifies pointer. Pointer pointing can be changed, and the value pointed to by pointer cannot be changed
  2. Const modifier constant pointer constant: const modifier is a constant. The pointer cannot be changed, and the value pointed to by the pointer can be changed
  3. const modifies both pointers and constants
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; error
	

	//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

Pointers and arrays

**Function: * * use pointer to access elements in array
example:

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;
}

Pointers and functions

//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

	swap2(&a, &b); //Address passing changes the arguments

	cout << "a = " << a << endl;

	cout << "b = " << b << endl;

	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

Pointer array function

Encapsulates a function that uses bubble sorting to sort integer arrays in ascending order

//Bubble sort function
 Bubble sort function parameter 1 first address of array parameter 2 parameter length
void bubbleSort(int * arr, int len)  //int * arr can also be written as int arr []
{
	for (int i = 0; i < len - 1; i++)   //Lateral circulation
	{
		for (int j = 0; j < len - 1 - i; j++)  //Medial circulation
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

//Print array function
void printArray(int arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << endl;
	}
}

int main() {

	int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
	
    // Array length
	int len = sizeof(arr) / sizeof(int);

	bubbleSort(arr, len);

	printArray(arr, len);

	system("pause");

	return 0;
}

Summary: when an array name is passed into a function as an argument, it is degenerated into a pointer to the first element

structural morphology

Structures are user-defined data types, allowing users to store different data types
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:

//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;
}

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 '.'

Structure array

**Function: * * put the user-defined structure into the array for easy maintenance

Syntax: struct structure name array name [number of elements] = {{}, {},... {}}

//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;
}

Structure pointer

**Function: * * access members in a structure through a pointer

  • Using the operator - > you can access structure properties through the structure pointer
//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, };
	
	//Pointer to structure variable
	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;
}

Summary: structure pointers can access members in a structure through the - > operator

Structure nested structure

**For example: * * each teacher tutors a student. In the structure of a teacher, record the structure of a student

Example:

//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() {
    //Create teacher
	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;
}

**Summary: * * in a structure, another structure can be defined as a member to solve practical problems

Structure as function parameter

**Function: * * pass the structure to the function as a parameter

There are two delivery methods:

  • pass by value
  • Address delivery

Example:

//Definition of student structure
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
};

//Value passing value passing modifier parameter does not change the argument
void printStudent(student stu )
{
	stu.age = 28;
	cout << "Name in subfunction:" << stu.name << " Age: " << stu.age  << " fraction:" << stu.score << endl;
}

//Address passing address passing changes the arguments
void printStudent2(student *stu)  //Receive address with pointer * stu
{
	stu->age = 28;
	cout << "Name in subfunction:" << stu->name << " Age: " << stu->age  << " fraction:" << stu->score << endl;
}

int main() {

    //Create structure variable
	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 passing plus&
	printStudent2(&stu);
	cout << "Name in main function:" << stu.name << " Age: " << stu.age  << " fraction:" << stu.score << endl;

	system("pause");

	return 0;
}

Summary: if you do not want to modify the data in the main function, pass it by value, otherwise pass it by address

Structure const

The function is to prevent misoperation

//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;

}

Structural case

Structural case

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:

struct Student
{
	string name;
	int score;
};
struct Teacher
{
	string name;
	Student sArray[5];
};

void allocateSpace(Teacher tArray[] , int len) //Receive teacher information with array
{
	string tName = "teacher";
	string sName = "student";
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++)
	{
		tArray[i].name = tName + nameSeed[i];
		//Add A when i =0
		
		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].name = sName + nameSeed[j];
			//The name of the j-th student of the i-th teacher = student + [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++)
		{
		//\Indent
		cout << "\t full name:" << tArray[i].sArray[j].name << " fraction:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main() {
//Random number seed
	srand((unsigned int)time(NULL)); //Random number seed header file #include < CTime >

	//Create teacher array (omit sturct)
	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;
}
rand() % 61 + 40 
Generate a random number 0-60(+40)
//Random number seed
	srand((unsigned int)time(NULL)); //Random number seed 
	Header file contains  #include <ctime> 

Posted by wisewood on Wed, 06 Oct 2021 08:34:10 -0700