Basics
-
The statement ends with a semicolon
-
compile
g++ name.cpp -o new_name # gcc for c language # g for c + +++
-
implement
./name
-
Standard library
- Core language: provides all building blocks, including variables, data types, constants, etc
- c + + Standard Library: provides a large number of functions for manipulating objects such as files and strings
- Standard template library STL: provides a large number of methods and data structures to supplement and expand the content of c + +
Namespace
-
Distinguish files with the same name in different folders
-
Definition: namespace name {}
-
Call internal method or variable name::code
-
When naming is specified, do not add name:using namespace name.
-
Nesting and splitting
data type
-
Basic type
type byte sign unsign bool Different from 01 char 1 -27 to 27-1 0 to 2 ^ 8 wchar_t 2 -215 to 215-1 0 to 2 ^ 16 int 4 -231 to 231-1 0 to 2 ^ 32 long int 8 float 4 double 8 long double 16 void No return value no type -
Enumeration type
enum Enumeration name{ Identifier variable, Identifier variable .... } Enumerating variables
By default, the first name is 0 and the second one is 1. If which assignment is assigned, the following will be incremented
-
Modifier
- short is used before int
- long is used before int and double
- signed/unsigned is used before int, char, short and long
-
Type qualification
- const program cannot be modified during execution
- volatile compilers do not require optimization
- The pointer decorated with restrict is the only way to access the object it points to
-
operator
- Arithmetic operator
- Relational operator
- Logical operators & |!
- Bitwise operators & | ^ (different is 1) ~ negation < < > >
- Assignment Operators
-
other
- sizeof
- ?:
- (...) give the value symbol of the last formula to the variable (similar to of js)
- . class / structure member
- (int)a mandatory replacement
- &A takes a address (& & and, & and, & A takes address, int & A alias)
- *a get objects by address
variable
-
Declaration: tells the compiler variable name, type, size, function name, structure name, size and other information, but memory will not be allocated at this time
type name
-
Definition: allocate memory after life variable, which can be regarded as "definition = declaration + allocate memory"
-
Local variables: manual initialization
-
Global variable: automatic initialization / manual initialization, automatic is 0 or \ 0 or Null
-
Constant: cannot be modified after definition
-
Integer:
- Prefix 0x/0 / decimal
- Suffix L signed / U unsigned
-
Floating point number:
- Decimal 3.14
- Index 3E5L
-
Boolean
- true
- false
-
character
- Normal ''
- Wide character L ""
-
Definition method
-
Use #define preprocessor to perform global and direct replacement without allocating memory during compilation. You can cancel redefinition through #undefine
#define LINE 10
-
Use const keyword to allocate memory locally and permanently
const int LINE=10
-
-
-
Storage class: defines the scope and life cycle of variables and functions
-
static: maintain the existence of local variables throughout the life cycle of the program. It is not necessary to create and destroy them every time they enter and leave the domain
-
extern: provides global variable references. All program files are visible. For variables that cannot be initialized, the variable name will point to a previously defined storage location
-
Mutable: it is only applicable to class objects and allows object members to replace constants, that is, mutable members can be modified through const member function
-
thread_local: declared variables can only be accessed on the thread they create
static int count = 10;
-
-
Custom structure
-
struct: it can store different types of variable data
struct name{ type1 name1, type2 name2 } objname; or #include <cstring> struct name{ type1 name1, type2 name2 } ; name obj1; strcpy(obj1.name1,Val)
-
As a function parameter
definition void func(struct typename name){name.key} call func(obj) definition void func(struct typename *name){} call func(&obj)
-
Use pointer
struct typename *name name = &obj name->key //Members must be accessed with arrows
-
-
Alias typedef: any type
typedef struct type_name{ type1 name1; } type_name name;
data structure
-
Array: an ordered collection of elements of the same type with a fixed size. It supports multi dimensions
-
statement
type name[size]={val} or type name[size];name[index]=val type name[][]={{}{}}
- The number of elements cannot be more than size
- No size or number
- Index assignment access, index starts from 0
-
Formal parameter
- void func (type *param) pointer
- void func (type param[size]) fixed length
- void func (type param []) variable length
-
Return: int * func()
- c + + does not allow to return a complete array as a function parameter. It returns a pointer to the array by specifying the array name without index
- c + + does not support local variable addresses returned outside functions unless the local variable is defined as static
-
-
character string
- char greeting[6]={'H','E','L','L','O','\0'}
- char greeting [] = 'hello' Auto ending \ 0
Process control
-
loop
- for(;😉{}
- while(){}
- do{}while{}
-
judge
-
if(){}
-
switch
switch(expression){ case condition: break default: }
-
?:
-
-
control
- break
- continue
- goto: label (any plain text): any statement
Input and output
-
Input: byte stream flows from devices (disk drives, keyboards, network connections, etc.) to memory
-
Output: byte stream flows from memory to devices (display screen, printer, disk drive, network connection, etc.)
-
<iostream>
- cin standard input cin > > args input value to parameter
- Cout standard output args < < cout is displayed on the display
- cout.width sets the field width
- cout.fill (STR) is not long enough and the field width is filled with str
- Cerr non buffered standard error stream cerr < < STR display screen immediately displays information, common language error
- Clog buffer standard error stream clog < < STR displays information when the display screen refreshes the cache, which is generally used for logs
-
< iomanip > formatted output
- setw set field width set (nun) < args is not enough. Fill in the front with a space
- precision (int) displays the number of decimal places
- setioflags (ios::flag) displays the setting, and the re prefix indicates the clearing status
- Common flag settings (multiple options for simultaneous connection are available)
- boolalpha can use the words true and false to represent Boolean values
- oct is displayed in octal
- dec is displayed in decimal system
- hex is displayed in hexadecimal
- left align
- Right align right
- Scientific scientific notation represents floating point numbers
- fixed represents a floating point number in a normal way
- showbase displays the cardinality of all values
- showpoint displays decimal points and extra zeros
- showpos displays the sign
- skipws skip white space characters when reading input, carriage return tab
- unitbuf empties the buffer after each insert
- internal returns the padding character between the symbol and the numeric value
- Uppercase hexadecimal uppercase output
- Lowercase hexadecimal lowercase output
- Common flag settings (multiple options for simultaneous connection are available)
-
< fstream > file processing
Classes and functions
class
-
Define class
#include <iostream> using namespace std; class Line //Class definition { public: //Public data Line(); //Constructor declaration Line(const Line &obj); //copy constructor friend void printWidth(Box box); //friend function ~Line(); //Destructor type name; type fun() //Normal member function declaration private: //Privatize data and prevent access double length; } // Member function definition //Ordinary member function type Box::fun(){} // Constructor Line:Line(void){} // copying functions Line:Line(const Line &obj) { ptr=new int; Copy value *ptr=*obj.ptr } // friend function void printWidth(Box box) // Destructor Line:~Line(void){}
-
Member type
-
Public member publuc, which can be accessed through object visit
-
Private member private
-
protected members
visit public protected private Like / friend y y y Derived class y y n External class y n n -
static: there is only one copy and all members share it
- When not initialized, create an object. The default setting is 0
- Cannot initialize within a class
- Initialize through classname::name outside the class
-
Static member function: static definition. Objects without classes can also be called through classname::name
-
-
encapsulation
- Data encapsulation: functions that bind and manipulate data
- Data abstraction: only expose the interface to the user and hide the concrete implementation
-
inherit
class Subclass: public/protected/private(default) Parent class 1, xx Parent class 2 //Modifier: member pre modification determines whether to expose, and class pre modification determines how much to inherit
- public:
- Parent public subclass public
- Parent protected subclass protected
- The parent class private does not inherit
- protected
- Parent class public, protected, child class protected
- The parent class private does not inherit
- private:
- The parent class is public, protected, and the child class is private
- The parent class private does not inherit
- Members not inherited: private
- Methods not inherited:
- Constructor, destructor, copy constructor
- overload operators
- friend function
- public:
-
polymorphic
class Shape { public: Shape(int a=0,int b=0){} int area(){} }; class Rectangle:public Shape{ public: Rectanle(int a=0,int b=0):Shape(a,b){} // Colon after constructor: partition function, assign value to member variable virtual int area() }
-
Calling an in class method
- Inline: Class Name:: method
- Objects: creating objects, objects method
function
-
At least main function
-
Definition: returntype name(type name1) {}
-
Transmission parameters:
- Value transfer: internally available and immutable
- Pass pointer: internally available and modifiable. When creating, int name(int *a){*a} and when using name (& A)
- Address: available internally and can be changed. When creating, int name (int & A) {a} and when using, name(a)
-
Anonymous function [] (Parma) {}
-
[] there is no defined variable. An error is reported when using an undefined variable
-
[&] any used external variable is implicitly referenced
-
[] any used external variable is implicitly passed in
-
[x, &y] x passes a value, and Y refers to it
-
[&, x]x passes value, other references pass in
-
[=, &y]x reference passed in, other passed values
-
In the form of [= [&], lambda can directly use this pointer [] () {this - > func()} ()
-
In the form of [], if you want to use this pointer, you must explicitly pass in [this] () {this - > func ()} ()
-
-
virtual function
- Dynamic link / late binding:
- Declare functions in the base class using the keyword virtual
- When a virtual function defined in the base class is redefined in a derived class, it is not statically linked to the function. At any point in the program, the function to be called can be selected according to the type of object to be called
- Static link / early binding:
- Use virtual to declare functions in the base class
- The function defined by the parent class will be used, and the compiler will be ready before the function call is executed
- Pure virtual function: defined first, no function body virtual int area()=0
- Dynamic link / late binding:
-
Constructor
- Executes each time a new object of the class is created
- Used to set initial values for some member variables, similar to init
- The name is exactly the same as the name of the class
- No value is returned, and void is not returned
-
Destructor
- Is executed each time multiple created objects are deleted
- The name is the same as the class, preceded by the tilde ~ name
- It does not return any values and cannot take any parameters
- Destructors help to free resources before jumping out of the program (such as closing files, freeing memory, etc.)
-
copy constructor
- When creating an object, use the previously created object in the same class to initialize the newly created object
- Usage:
- Initialize a new object by using another object of the same type
- Copy the object and pass it as an argument to the function
- Copy the object and return it from the function
- If there is no copy constructor defined, the compiler will create one by itself
- If the class has pointer variables and dynamic memory allocation, there must be a copy constructor
-
Inline function:
-
During compilation, the compiler places the code copy of the function in each place where the function is called, rather than at runtime, so as to improve efficiency and change space for time. Therefore, generally, inline functions are relatively short and need to be reused
-
Class member functions are mostly inline functions
inline int Max(int x,int y){}
-
-
Friend class / function: defined outside the class, but has access to all members of the class, including public, protected and private
Pointer
- The pointer points to the address, which is essentially a special variable whose value is the address
- Each variable occupies a memory location and has a unique address & get
- The actual data type of the value of the pointer is a hexadecimal number, and the data type of the variable or constant pointed to is different
- Declare type *name, Null pointer, value 0
- Use name = & param
- Formal parameter void func (type *name)
- Return iny * func()
- Support multi-level pointer. The pointer pointing to the address of the pointer can be modified with n+1 level pointer
- Point to array address int *p=int var []
- Point to class and structure class/struc *name=param
- Pointer movement p + +, p –
- This: each object can access its own address through this pointer. This pointer is the implicit parameter of all member functions. Friend functions do not have this pointer, because friend functions are not members of a class and only member functions have this pointer
quote
-
Alias a variable and access it with a reference variable or variable name
-
Difference between and pointer
- The reference must be connected with a legal address, and the pointer can be Null
- When a reference is initialized as an object, it cannot change the point. The pointer can change the point at any time
- References must be initialized at creation time, and pointers can be initialized at any time
-
Syntax: Type & name = Val
-
By using references instead of pointers, the program is easier to read and maintain
-
A function can return a reference in the same way as a pointer
-
When the function returns a reference, it returns an implicit pointer to the return value, and the function can be placed on the left of the assignment statement when used as a variable
-
The referenced object cannot exceed the scope, so it cannot return a reference to a local variable
-
You can return a reference to a static variable
heavy load
-
Overload decision: multiple overloads automatically select the most appropriate one instead of covering the front
-
Overloaded function: the number of parameters, type or order must be different
-
Operator overloading
class Name { public: Name operator+(const Name& b){} } Name name1 Name name2 Name name3 name3=name1+name2
-
Reloadable:
- Binocular arithmetic operator ± * /%
- Relational operator = =! = < > < = >=
- Logical operator | & &!
- Monocular operator ±*&
- Self increasing and self decreasing + ±-
- Bitwise operators & ~ ^ < > >
- Assignment operator = + = - = * = / =% = | = ^ = < = > >=
- Space application and release new delete [] delete []
- Other operators () - >, []
-
Cannot be overloaded
- Member accessor
- Member pointer accessor - >
- Domain operator:
- Length operator sizeof
- Conditional operator?:
- Preprocessing symbol#
Common library
-
< cmath > mathematical correlation
double cos/sin/tan/log/sort/fabs(double) Cosine, sine, tangent, logarithm, square, absolute value double pow/hypot(double,double) Exponent, square root of sum of squares int abs(int) absolute value double floor(double) Returns the largest integer less than or equal to the passed in parameter
-
< cstdlib > random number
srand(unsigned int seed) j=rand() Random number, no addition srand The generated is a pseudo-random number
-
< CString > string operation
strcpy(str1,str2)copy s2 reach s1 strcat(str1,str2)Connection string strcmp(str1,str2)For comparison, the same 0, 1 returns negative, and 2 returns positive strlen(str)String length strchr(str,char)Return pointer str in char First occurrence position strstr(str1,str2)Return pointer str1 in str2 First occurrence position
-
<string>
str3=str1+str2 Splicing str1=str2 copy str.size()length
-
< crime > time dependent
lock_t,size_t,time_t The system time and date can be expressed as some format integer tm Put the date and time in c In the form of structure, tm The structure is as follows struct tm{ int tm_sec;second int tm_min;branch int tm_hour;Time int tm_mday;What day is it in January int tm_mon;month int tm_year;Since 1900 int tm_wday;What day of the week int tm_yday;What day of the year int tm_isdst;Daylight saving time } ctime()Convert to string gmtime()convert to tm time_t now =time(0)Date and time of the current system time_t time(time_t,*time)Returns the current calendar time of the system char *ctime(const time_t *time)Returns a string pointer representing the local time struct tm *localtime(const time_t *time)return tm Local time pointer in format clock_t clock(void)The time taken by the processor since the program was executed double difftime(time_t time2,time_t time1)time1 and time2 Seconds difference between size_t strftime()Format the date and time in the specified mode
-
< fstream > file operation
data type ofstream The output file stream is used to create and write files w ifstream The input file stream is used to read information from the file r fstream The above two file streams are available at the same time wr Member function Open file ofstream outfile; outfile.open(const char *path,mode1|mode2) ios::app Append mode, all writes are appended to the end of the file ios::ate Navigate to the end after the file is opened ios::in Open file for reading ios::out Open file for writing ios::trunc If the file exists, its contents will be truncated after opening, that is, set the file length to 0 Close file putfile.close() Relocation pointer Location: ios::beg start ios::end ending ios::cur current location file.seekg(n)Locate to f Start back n byte file.seekg(0,iOS::end)Navigate to the end of the file file.seekg(n,iOS::cue)Moves the read pointer back from its current position n Bytes file.seekg(n,iOS::end)Move the file pointer back from the end n Bytes
-
< thread > thread operation
std::this_thread::get_id()Get main thread id std::this_thread::sleep_for()dormancy std::thread name(func)Create thread name.join()Stop and recycle
Dynamic memory
-
Memory structure
- Stack: all variables declared inside the function occupy stack memory
- Heap: unused memory that can be dynamically allocated when the program is running
-
grammar
- Apply for new
- Delete delete
-
array
//one-dimensional distribution int *array=new int [m] release delete [] array //two-dimensional distribution int **array array=new int *[m] for(int i=0;I<m;I++){ arrat[i]=new int [n] } release for(int i=0;I<m;I++){ delete [] array[i] } delete[] array //three-dimensional distribution int ***array array =new int **[m] for(int i=0;I<m;I++){ array[i] =new int *[n] for(int j=0;j<n;j++){ array[i][j]= new int [h] } } release for(int i=0;i<m;I++){ for(int j=0;j<n;j++){ delete[] array[i][j] } delete[] array[i] } delete[] array
Template
-
The foundation of generic programming is to create blueprints and formulas for generic classes or functions
-
It enables the user to declare a general pattern for a class or function, so that the parameters and return values of some data members or member functions in the class can obtain any type. When writing logic, it is not limited to types
-
Template function
template <class T> void swap(T& a,T& b){} ab by int Time swap(int &a,int &b) ab by str Time swap(char &a,char &b)
-
Template class
template <class T> class A { public: T a; T hy(T c,T &d) } template<class T1,class T2> void A<T1,T2>::h()
Preprocessor
-
#At the beginning, the preprocessing that needs to be completed before compiling
-
Not a c + + statement, no semicolon end
-
#include includes the header file into the source file
-
#define create symbolic constant
- #define NAME valu
- #define NAME(args)(operation)
-
#if condition
#endif
-
Predefined macros (system constants)
- __ LINE__ Line number
- __ FILE__ file name
- __ DATE date
- __ TIME__ time
SLTL Standard Template Library
container
-
< vector > vector
- push_ Insert at the end of back. If the size exceeds, expand the capacity
- Size size
- begin returns the beginning iterator
- End returns the iterator at the end
-
< list > List
-
< Map > mapping
-
<memory>
-
< queue > queue
-
< deque > dual queue
-
<priority_ Queue > priority queue. The element order is determined by some predicate acting on the stored value pair
-
< set > set, a red black tree composed of nodes
-
< multiset > multiset
-
< stack > stack
algorithm
-
<numeric>
- accumulate(v.begin(),v.end(),0) is added to 0 from begin to end
-
<functional>
-
<algorithm>
- reverse(v.begin(),v.end()) array transpose
- sort(v.begin(),v.end()) sort
iterator
- <iteration>
- <utility>
Tips
-
Explicit implicit
#include <iostream> using namespace std; class A{ int x; public: } void main() { A a1;Implicit call A() A *a2=new A(10) Explicit call A(int a)Overloaded A() delete a2 The destructor was implicitly called~A() } The destructor was implicitly called at the end of the program~A()
-
&Variables: reference addresses
*Address: access the variable value of the address
-
Rewrite: same name, same parameters, different logic
Overload: different parameters with the same name
-
this is equivalent to self. You must use - > to access the property
-
You need to hide private. No one can use it except yourself
Semi hidden protected is required, and subclass friends can use it
versual needs to be rewritten
-
For use only void does not return data
-
exception handling
c++-python try-try catch-except throw-raise Example throw str try{}catch(){} try{}catch(){}
-
CONCAT(str1,str2) splice string
-
The pointer defines * name, assigns or uses the address to be saved, and uses & Val or & name
-
Function can only return one object, so int/str single object can be returned directly. Array / struct needs to be wrapped into an element with the help of pointers