C++ programming [Tan Haoqiang] Part 2: Process-oriented programming

Chapter 3 Preliminary Program Design

Algorithm: the methods and steps used to solve the problem (numerical and non-numerical algorithms)

C++ programs include:

(1) Preprocessing command: #include or #define

(2) The declaration part: the declaration of data types and functions, there are declarations inside the function, and there are declarations outside the function

(3) Function

Three basic structures of the program: sequence structure, selection structure and loop structure

Global variables and local variables: the local variables declared in the function, the scope to the end of the program; the global variables declared outside the function, the scope ends outside the function

Nine kinds of control statements in C++:

(1) if conditional statement

(2) for loop statement

(3) while loop statement

(4) do...while loop statement

(5) continue to end this cycle and start the next cycle

(6) The break is terminated and can only be used in switch structure or loop structure

(7) switch branch selection statement

(8) Goto statement

(9) return returns from the function

The definition of statements in C++: statements that can achieve a certain operation and end with a semicolon are all statements

Basic input and output methods in C++:

(1) Input and output stream: cin cout

(2) getchar and putchar functions for single character input and output

(3) Scanf and printf functions for input and output

Compared with C, C++ introduces logical data, namely bool type, whose value is one of true or false

Conditional expression: This feeling is not very common. Its expression is for example (a> b)? a:b; If the brackets are true, the value before the colon is taken; if the brackets are false, the value after the colon is taken value. This conditional operator is also the only ternary operator in C++

Which one is used for switch statement or multiple if statement?

If it can be realized by switch statement, it can be realized by if, but the opposite is not necessarily true. If it is an interval range, use if, and if it is equivalent, use switch.

The while statement and for statement in the loop statement: when the loop times are known, the for statement is better; when the loop times are unknown, the while statement is better (the while statement only gives loop conditions). In fact, the for statement is the most extensive and flexible. It can be used for unknown loop times and can completely replace the while statement.

Example: A program for estimating the pi ratio (based on the mathematical formula of π/4)

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main(void)
{
	int s = 1;
	double n = 1, t = 1, pi = 0;
	while (fabs(t) > 1e-7)
	{
		pi = pi + t;
		n = n + 2;
		s = -s;
		t = s / n;
	}
	pi = pi * 4;
	cout << "pi = " << pi << endl;

	return 0;
}

In addition, the related small algorithms for loops include the Fibonacci sequence problem of rabbit reproduction, the problem of finding prime numbers, the problem of code encryption, etc.

Chapter 4 Functions and Preprocessing

Large programs are best divided into modules. The main function calls other functions, and other functions can also call each other (but functions cannot be nested definitions). The main function is often written very simply, and its role is to schedule.

When the calling function calls the called function, the calling function passes the actual parameter values ​​to the formal parameters in the called function. In C++, the function type and function parameter type must be specified at the same time when defining the function.

Note for function call:

(1) The called function can be a library function or a function defined by the user

(2) If it is a library function, you need to use the #include command at the beginning of the file to include the relevant header files in this folder

(3) If it is a function defined by the user, the function and the calling function need to be in the same program unit, and it is determined whether a declaration is required according to the location

Overloading of functions:

Generally speaking, a function corresponds to a function, but sometimes what we want to achieve is the same type of function (for example, in a function with a larger size, my input data type may be different, so different data types have to write a function , This is too much trouble). Therefore, C++ allows multiple functions to be defined separately with the same function name. The number of parameters and parameter types of these functions are different. This is the overloading of functions [one thing, multiple uses] . An example is << can be used as an input and output stream operator, but also as a shift operator.

Function template:

Compared with function overloading, function overloading still has to define multiple functions, but the function names are consistent. The great thing about the function template is that it establishes a general function, and its function type and formal parameter type are not specified.

Examples of using function templates:

template <typename T>  //模板声明,其中 T 为类型参数
T max(T a,T b,T c)     //定义一个通用函数,用 T 做虚拟的类型名
{
    if (b>a)
        a = b;
    if (c>a)
        a = c;
    return a;
}

Functions with default parameters:

A default value is given to the formal parameter when defining the function, so that the formal parameter does not have to take the value from the actual parameter. If you do not want the formal parameter to take the default value, it is given separately through the actual parameter. For example, such a function declaration:

float area(float r = 6.5);  //函数声明


area()     //形参拿到了6.5,相当于 area(6.5)
area(7.5)  //形参拿到了7.5

Recursive function call:

No need to consider the details of the process of implementing recursion, just write the recursive formula and the recursive end condition (ie boundary condition) to easily write a recursive function

Use register to declare register variables: If some variables are used very frequently, it takes a lot of time to access the variable session, so you can put the variable in the register, for example:

register int i;

The preprocessing functions of C++ include the following three types:

(1) Macro definition

#define PI 3.1415

(2) File contains

#include "file2.cpp"              //用户编写的头文件,在当前路径下
#include "C:\tan\C++\file2.cpp"   //用户编写的头文件,带绝对地址
#include <iostream>               //系统头文件常用<>

(3) Conditional compilation

It’s not used much, so it’s omitted here.

Chapter 5 Arrays

An array is a collection of ordered data belonging to the same data type. Finding an element in an array requires two elements: the array name and the subscript (in C++, square brackets are used to indicate the subscript). The storage of the array is continuous, occupying one block. Contiguous memory space.

Note that the definition of an array is very similar to the way of indexing (reference), don’t confuse

Example of initialization of one-dimensional array:

int a[5] = {1,2,3,4,5};
int a[] = {1,2,3,4,5};   //赋初值时可以不指定数组的长度
int a[5] = {1,2,3};      //赋初值时可以只给一部分元素赋值

Example of initialization of a two-dimensional array:

int a[2][3] = {
   
   {1,2,3},{4,5,6}};  // 同理也可以写在一个花括号内

Compared with C, C++ adds a new data type-string type string. Before this string type is not used, only string arrays can be used, and string functions must be used for operations, such as strcat (connection), strcmp (comparison) ) And strcpy (copy), and simple operators can be used directly for the string type. For example, the assignment sign = can be used directly for string copy, the plus sign + can be used directly for string concatenation, and the relational operation such as> can be used directly for string comparison. symbol. For example:

//字符串复制
string1 = string2
//字符串连接
string = string1 + string2

Chapter 6 Pointers

The pointer is the memory address of the variable, and the pointer variable is the variable with the address!

int * p is to define a pointer variable p of type int *

*p is to access the value stored in the address stored in p

p = &i is to give the address of i to the pointer of type int *

There is also an important role for pointers! ! ! That is, the pointer is passed to the function as a parameter! What's the use of this? Looking back at the function we talked about earlier, it only returns a value. Suppose we define a constant in the calling function and want to change this constant by calling the function. Then just passing this constant into the called function is all right, because the memory is released after the called function is executed. At this time, the address of this constant must be passed to the called function as a parameter. , So that the called function can change the value in the calling function.

Array and pointer: The name of the array is the address of the first element of the array, which coincides with the pointer. The pointer and the array are naturally closely related. For example

//下面两者等价
p = &a[0];
p = a;

So p[i] = a[i] = *(p+i) = *(a+i), respectively corresponding to the subscript method and the pointer method

Another important concept of C++- reference . This is a supplement of C++ to C. The function of reference is to give an alias to a variable. For example, here b and a are one thing, which is equivalent to an alias, and & is a reference declaration Symbols, so many problems that can only be solved with pointers can be solved with references

int a;
int &b = a;  //声明b是a的引用

Chapter 7 Custom Data Types

Structure type : struct

Comparing structure and array, the elements in the array belong to the same type, but sometimes it is not enough to have a single data processing task, so there is a structure type

Structure variables and pointers:

//下面三者等价
stu.num;
(*p).num;
p->num

Structure variables and pointers combine to form a linked list

Static linked list and dynamic linked list, if used, it is still based on dynamic linked list

The difference between dynamic memory allocation in C++ and dynamic memory allocation in C language: C++ uses new and delete to replace malloc and free functions, but it should be noted that both new and delete here are operators, not functions, so its The execution efficiency is very high. Although malloc and free are reserved in C++, they are not recommended.

Examples of the use of new:

int * p = new int;             //开辟一个放整形的存储空间,返回一个指向该空间的地址
int * p = new int(100);        //开辟一个放整形的存储空间,并赋这个整形初值为100,返回地址
float * p = new float(3.14);  //开辟一个空间,里面放初值3.14,返回该空间地址给指针变量p

Examples of the use of delete

delete p;

Union type : union

Similar to the structure, but it is to store several different variables in the same memory, and the memory length is equal to the length of the longest member, that is to say, they cover each other, so it is called a union

Enumeration type : enum

enum weekday {sun,mon,tue,wed,thu,fri,sat}

Examples of using typedef to declare types:

typedef struct Node
{
	int id;
	char name[5];
}NODE, * PNODE;

 

Guess you like

Origin blog.csdn.net/weixin_43450646/article/details/106967504