Basic C + +

Source: Internet
Author: User

Basic C + +

Transferred from: http://blog.csdn.net/fangbaolei2088/article/details/7990519

1. Compiler g++
g++-C Compiles no connections, generates. o Files
g++-O modifies the name of the file generated after compilation (default is A.out)


2.c++ Advantages
Supporting data abstraction
object-oriented
Contains all C Features
Portable and efficient as C
Can is linked to existing C libraries and functions (!!)
...


3. Variable name
The first letter must be a letter or an underscore
Use only letters or underscores or numbers
There can't be spaces in the middle
Cannot be a reserved word and cannot have the same name as a library function
Case sensitive


4. Basic data types
Char=> unsigned/signed Char
int=> unsigned/signed Long/short int
Float=> Double, long double
bool


5. Four type conversion operators (see details later)
Static_cast:
Const_cast:
Reinterpret_cast:
dynamic_cast:


6. Operators
Top three priority: (). or single-mesh
Priority after three:?: = Comma


7. Enumeration type
Enum color{red, blue=10, GREEN}; The default value is 0, 1, 2 ... this changes the value after 0, 10, 11 ...
Color C = GREEN;


8. Expressions (slightly)


9. Control statements
if () {}else{}
while () {}
Do{}while ();
For () {}
Switch () {case;}


10. Functions
Function three elements: return type, function name, parameter table
Declaration (no function body; parameter table parameter can have no parameter name, but must have type)
Definition (with function body {})
The call function is actually using the stack operation, when the completion of a function, stack release
Use default parameters (default values must be specified from right to left)


11. Inline function (inline)
At compile time, just paste the code of the inline function into the call, not into the stacks operation, so fast
Must be declared with the definition put together
Control statements are not supported (so the inline function is seldom used in practice)


12. Recursive functions
function calls itself
Must have an end condition
Stack operation


13. Function overloading (overload)
Overloaded functions differ at least in number, type, and order of parameters
Try not to use default parameters for functions that prevent calling conflicts


14. Const qualification of function parameters
You can prevent the value of an incoming parameter from being modified in a function


15. Scope and visibility of variables (☆)
Local variables: stored in the stack; function call is finished; scope this function inside
Global variables: stored in the global data area, program end release, scope source files, other sources use the extern declaration
Static local variable: stored in the global data area, initialized only once for the first call to the function, and within the scope of the function
Static global variable: stored in Global data area, program end release, visible range origin file (other source file not visible)


16. Header file (. h)
declaring functions
struct
Class
Enum
extern declaration variables (global variables that use other source files)


17. Process Space
Data
Heap
Code
Stack


18. Arrays
Only when declaring uninitialized, must have the number of elements
Curly brace initialization must be put together with the declaration (the number of elements can be omitted when the curly brace is initialized)
Note the semicolon after the curly braces
Character array initialization available double quotes
Good habits: memset (buf, 0x00, sizeof (BUF)); Memory can be initialized with arrays, structs, and so on


19. Structure (struct)
struct names defined with structs can be used as a new data type

Such as:
struct person{...;};
Person P1; It ' s correct
struct person p2; It ' s correct too

Note The final semicolon when defining the structure!!
Can be assigned between structures
Take up memory space (Unix/windows natural to the bounds, the structure size must be the largest member of the whole number of times, Linux only need to complete the integer multiples of int)


. Pointers
To prevent wild pointers , it is best to assign values immediately when declaring pointers (NULL)

Note the use of the * number:
When declaring: int* pi = NULL; The asterisk here indicates that the variable pi is a pointer -type variable
When assigning: pi = &i; Here the direct use of the PI,PI variable is stored in address 0x ...
When used: *pi = 5; Here the asterisk denotes the variable I pointed to by the pointer , which is equivalent to i = 5;


21. Structure fetching members
struct variable FETCH member: P.id
pointer to struct to take member: Pp->id or (*PP). Id


22. The array name is actually a constant pointer (not self-add and subtract)


23. String manipulation (#i nclude)
strcpy (target, source);
Strlen ();
strcmp (target, source); Same return 0
STRNCMP (target, source, n); Comparison of N characters
strcat (target, source);


24.C style strings and C + + style strings
C style string:char* or char []
C + + style string:string
(!!! Note: In Unix C, most library functions and system functions still use C-style strings)
These two types of strings can be converted to each other:
C style to C + + style:string a = b;
C + + style to C style:char* B = a.c_str (); Use the C_str () function, or use the data () function


25. Using heap space (heap) for dynamic memory allocation
int* p = new INT[10];
Delete[] p; Just release P point to the memory, release the memory after other programs can be used, otherwise memory leaks
p = NULL; Assign the P pointer to NULL to prevent the wild pointer


26. Function Pointers
!!! Note: A function pointer is a variable, not a function

Such as:
void (*PF) (int, int); PF is a pointer variable that can only point to a function of the void f (int, int) class!!!
void f (int a, int b) {...}
PF = f; The first address of f is deposited into the PF variable!!!

function pointers are typically used only when declaring arguments to a function
(That is, when the function FA needs to call another function FB, the function pointer of the FB is placed in the argument list that declares FA)

Such as:
int fa (int a, void (*PF) (int, int)) {...}//calling the function FA, only one pointer to the void f (int, int) function can be passed in the second argument
void fb (int a, int b) {...}
void (*PF) (int, int) = FB;
FA (5, PF);


27.void Pointer
Function parameters are generally used as function declarations to increase function versatility
Do not perform self-addition and subtraction operations


28. Constant pointer and pointer constants
Constant pointer : const int* p; The data that P points to is immutable (p points to constant)
pointer constant: int* const p; P Immutable (must initialize)


29. References
Reference is an alias of a variable
Declaration:int& ri = i;
Used: ri = 5; Equivalent to using I itself (i=5)
Often used to do function parameter passing


30.typedef alias to type
Steps:
Declaring a variable or function
Change the name to an alias
Front plus typedef

★c++ Object-oriented features


1. Class
A struct that encapsulates a function member
(In fact, in C + +, structs can also encapsulate functions inside, but it is customary for structs to encapsulate data only, class can encapsulate data and functions)
Increase member access rights (public, private, protected)
Class default is private (struct defaults to public)
Private=> can only be accessed by this class or friend
Protected=> can only be accessed by this class or by friends or sub-class
Public=> All public
The member functions of the external definition class are used with the domain modifier (::).
Pay attention to the semicolon!!


2. Constructors (constructor)
The role of initializing objects when creating objects
Names and similarities
Only for public!!
No return type!!
can be overloaded!!
No system is added automatically (once defined, the system is no longer added)
You can use a colon (:) to elicit an initialization list, such as:
Person::P Erson (int A, int. B): ID (a), age (b) {}//assigns a member ID to a, and member age is assigned a value of B
Structs can also use constructors


3. Copy constructor (copy constructor)
The system defaults to a copy constructor, which copies the members sequentially (shallow copy), which is dangerous when a pointer member is present
Initializes other objects of the same type with an existing object
Person (const person& PA);
Use: Person P2 (p1); Equivalent to assigning all members of the P1 to P2


4. destructor (destructor)
~ Class name () {}
No return type!!
Do not reload!!
No Parameters!!
System calls automatically
Do cleanup work


5. Inheritance
Inheritance mode public, protected, private
Class Derived:public base{};
subclasses inherit all members of the parent class , but cannot access the private members of the parent class
The member property inherited by public is not changed
Protected inherited member public becomes protected, other unchanged
Private inherits all the changes to private

Inherited constructors, the system calls the parent class before calling the subclass
the constructor of a subclass can pass parameters to the constructor of the parent class , such as:
Person::P Erson (int A, int. B): ID (a), age (b) {}
Student::student (int A, int b, int c):P Erson (A, B), Grade (c) {}//pass parameter A to the constructor of the parent class , b

The destructor in the inheritance, the system first calls the subclass and then calls the parent class

Overwrite: A function in a subclass overrides a function of the same name in the parent class


6. Polymorphism and Virtual functions
To resolve the overwrite problem, declare the function of the parent class as virtual (virtual), and then define the function with the same name in the subclass
When a pointer to the parent class is used to point to the subclass object, the object type is automatically recognized when the function is called, and the function in the corresponding subclass is called
Such as:
virtual void Person::d isplay () {cout << ' person ' << Endl;}//declared as virtual function
void Student::d isplay () {cout << "Student" << Endl;}
person* p = new Student;
P->display (); Calling the display of a subclass
Show as "Student"


7. Pure virtual function
If the function of the parent class is empty, you can declare it as pure virtual function only in order to use polymorphism
virtual void display () = 0;


8. Multiple inheritance and virtual inheritance (Diamond inheritance) (not commonly used)


9. Explanation of type conversion operator
Static_cast:void between pointers and other types of pointers
Const_cast: Converting between constants and variables
Reinterpret_cast: Conversion between pointers and integer data; conversion between arbitrary types of pointers
dynamic_cast: A conversion between classes that have an inherited relationship and a virtual function to succeed the child to the parent
Format: xxxx_cast (data)


10. Abstract data Type ADT
Abstract classes cannot create objects


11. Friend (Friend)
Authorize functions or other classes outside of this class to use all members of this class (including private members), using "Object. xxxx"


12. Constant member functions
The member function parameter list of a class is followed by a const, which indicates that the function is a constant member function and cannot modify members of this class, such as:
The member data of this class cannot be modified in void display () const{}//display


13. Static Members
Static data members: All objects use one copy of data; Outside the Initialization class (::); Access is also used (::)
Static function member: equivalent to a global function; only static data members can be accessed; outside the Class (::); Access by (::)


14. Operator overloading
Define "operator ..." as a function name
The return type cannot be empty!!
Method: Member or Friend (try to member)
Operand of operator cannot be changed (exception of parentheses, special operand of parentheses)
Operators that cannot be overloaded:. . *::?: sizeof # # #
Operators that manipulate primitive types cannot be overloaded (that is, at least one of the operands of an operator should be a custom type, such as a class)

can only be overloaded with member functions: operator= operator[] operator () operator-> operator->*
When a member function is overloaded, the default first operand is always the object itself!!! So the first operand of the parameter list can be omitted!!!

:operator<< operator>> that can only be overloaded with a meta function
When the first operand is not the object itself, the UF element should be!!!

The overloads of several operators are described in detail below:

▲operator=
When a class does not have a custom operator=, the compiler automatically generates a pointer member when it is dangerous
member function overloading only
Common formats:
a& operator= (const a& AO)
{
if (this = = &ao) return *this; Determines whether the this pointer points to the address of the AO object
...=...;
*.. =*..; Pointer member assigns the variable to which it points
return *this;
}

▲operator++ () and operator++ (int) before Plus and after
When these two functions are defined, the former is called when using ++a, and the latter is called when using a++
Mute element Distinction
Pre-Gaga format:
a& operator++ ()//Use reference
{
...++;
...++;
return *this;
}
Format of post-Gaga:
A operator++ (int dummy)//cannot use reference
{
A temp = *this;
...++;
...++;
return temp; Returns the value before the add
}

▲ Binocular operator
As a member function overload, the first operand must be the object itself and can be omitted from the argument list!!
When the first operand is not the object itself, it should be a method of the element!!

▲operator ()
Special, the number of operands is indeterminate
When using a similar function called functor (functor), the actual function is more powerful than the function.

▲operator New/delete
More special, fixed format
Static void* operator new (size_t sz) {}//must be static, return void*
static void operator Delete (void*) {}
New and delete can be brought together []

▲ Conversion Operators
Used to convert an object to another data type
Format is special and does not write return type (its type name is the return type)
Such as:
Operator double () {}//will return a double type variable
Use:
Double (AO);

▲operator<< and Operator>>
These two stream operators must be overloaded as Friend
The format is more fixed:
ostream& operator<< (ostream& o, a& ao)
{
O << .... << ... << ...;
return o;
}

istream& operator>> (istream& i, a& ao)
{
I >> .... >> ... >> ...;
return i;
}

15.main command line parameter mode
int main (int argc, char* argv[])
ARGC refers to the number of command-line arguments, including the command itself
ARGV stores each parameter, including the command itself, which is argv[0]
argv to char*[] type, i.e. char** type, or char[][] type, equivalent to two-D character array or one-dimensional string array

16.I/O Standard Flow
(Cin, cout, Cerr, clog)
CIN and cout support buffering, support redirection
Cerr for error message output, buffering not supported, redirection not supported
Clog for log output, redirection not supported

Cin Detailed:
CIN >>//continuous use; with blanks (including spaces, carriage returns, TAB) as separators
Cin.get (char c)//can be used continuously; get any single character, including whitespace
Cin.getline (char* buf, sizeof (BUF), ' \ n ')//can be used continuously; Gets a row, ending with the last specified character, can include blank, default carriage return
Cin.gcount ()//Count
Cin.read (char* buf, sizeof (BUF))//can be used continuously, read the content of the specified size, including white space; The first argument must be char*, the cast is available
Cin.ignore (' \ n ')//ignores content of the specified size, ignores the character ending, and is often used to empty the buffer
Cin.clear ()//clear error state; often followed by ignore
if (!cin)//error is determined; CIN is false
Cin.peek ()//view buffer next character, but not read, that is, use get time can also read
Cin.putback ()//returns the last read-back character to the buffer, not commonly used

cout Detailed:
cout <<
Control: Endl, flush ....
Cout.put (char)
Cout.width (int)//one-time command
Cout.fill (char)
cout.precision (int)
COUT.SETF (iOS:: ...)
COUT.UNSETF (iOS:: ...)
(cout These commands are not commonly used, the functions in the common header file are replaced)

:
SETW (int)//Set width
Setfill (char)//Set fill character
setprecision (int)//Set precision, total number of digits when single, and number of digits after decimal point when combined with fixed

17.I/O file stream
(need to include header file)

Ifstream class:
Use: ifstream fin; Create an object fin
Functions that can be used in CIN can also be used in fin
Extensions to CIN:
Constructors can make filenames and open methods
Fin.open (...)
Fin.read (...)//More Use this function to read
Fin.is_open ()//Check whether open successfully, in fact often replace this function with if (!fin)
Fin.eof ()//Determines whether the end of the file exceeds the end and returns True
Fin.close ()//close file

Ofstream class:
Use: Ofstream fout;
Common open methods are: Ios::binary Ios::app ios::out
(the remaining ibid.)


Common Write/Read formats:
Fout.write ((char*) &a, sizeof (a)); Writes the data of a object to a file; note forced type conversion (char*)
Fin.read ((char*) &b, sizeof (b)); Read the contents of a file into the space of a B object

18. Exceptions (Exception)
(#i nclude)
Try
{
....;
if (...)
{
Throw ...;
....; Will not execute this sentence
}
}
catch (...)
{
....;
}

Attention:
Catch catch exception is the same type of data as throw
After catching an exception, the program resumes execution where the catch has been processed and does not return a throw
After an exception is generated, the program jumps immediately and does not execute the statement under throw
If no catch catches an exception that has already been thrown, the final kernel snaps to an exception will force the program to shut down gracefully
catch (...) (three points in parentheses) to catch any type of exception
The type of the exception is often defined using an inner class (inner class)

19. Inner Class
An inner class belongs to the class member of the class it is in (that is, the static member of the class) and does not belong to an object
The data in the inner class is not the same as the data of the class it is in

★ Data Structure


1. Linked list (linklist)
is composed of nodes, each node can be a struct, and the struct can be encapsulated into the structure, destructors and other functions (and often so)
Each node can be defined as follows:
struct Node
{
Data data; Adt
Node* Next; pointer to next node
Node (const DATA D)//constructor initialization nodes
{
data = D;
Next = NULL;
}
};

Each linked list is accessed by one head pointer Head (node* head;)

Basic operation: increase, delete, check, change

▲ Insert Node (increment):
node* p = new Node; Allocate space for new nodes
P->data = 0; P->next = NULL; Initializes a new node (this can be encapsulated in the node's constructor)
Look for the location to insert (that is, the next point of the previous node, assuming LP)
P->NEXT = LP; Point next to the next node where you want to insert the new node
LP = P; The next node in the insertion position points to the new nodes
Insert Successful

▲ Delete node (deleted):
node* temp = p->next; Save the next pointer that will delete the node (that is, the address of the next node of P)
Delete p; Remove space for P
LP = temp; Next node of p node points to the next point of P
Delete Succeeded

▲ Find Node (check):
node* p = head; Start traversing from the beginning of the pointer
while (p)//p is not NULL, it continues to traverse
{
if (P->data = = finddata) break;
p = p->next;
}
Disadvantage: The so-found p, only the value equals p the previous node's next value, and not its previous node's next itself!!!
To get to the previous node's next itself is also very simple, just need to define a pointer , traverse when the pointer lag one step
Such as:
node* p = head;
node* LP = NULL; Always lag P one step
while (p)
{
if (P->data = = finddata) break;
LP = P;
p = p->next;
}
The resulting LP is a pointer to the previous node of P, the value of Lp->next and p should be equal, and Lp->next is the data in the list itself!!

▲ Modify Node (change): slightly

▲ Delete all nodes:
Ways to always delete head nodes
node* p = head;
while (p)
{
p = head->next; Save the address of the next node of the head node
Delete head;
head = p;
}
Delete Complete

▲operator[]: Slightly


2. Stacks (Stack)
LIFO (last on first out)
Common operations: Push (), pop (), IsEmpty (), Clear ()
(when actually used, the stack operation always separates the pop function as top and pop two, top just access, pop delete)
Can be implemented with arrays or linked lists
Arrays: subscripts
Linked list: Pre-insertion pre-fetch


3. Queuing (queue)
FIFO (first in first out)
Can be implemented with arrays or linked lists
Arrays: subscripts
Linked list: Post-insertion pre-fetch
Priority queue: Auto-sort on insert


4. Two fork trees (binary tree)
Advantages of Set arrays and linked lists: Quick Find (array), easy to insert data (linked list)
A maximum of two child nodes per node
So each node consists of two node pointers left and right
struct BNode
{
Data data;
Bnode* left;
bnode* right;
BNode (const DATA D)//constructor
{
data = D;
left = NULL;
right = NULL;
}
};

Accessed by a pointer to root of the roots node (bnode* root;)
Generally by recursive implementation operation!!


5. Two-fork search tree (binary search trees)
Left dial hand nodes (including child nodes of child nodes) must be smaller than the parent node
Right child node (including child nodes of child nodes) a point greater than or equal to the parent node

Common operation: increase, traverse, delete, check, change
Generally use recursive method to achieve!!

▲ Insert Node (increment):
void Insert (bnode*& ptr, bnode* pnew)//ptr is the location to insert the tree (you must use a reference to the pointer !!) ), Pnew is the node to be inserted
{
if (ptr = = NULL)//When the tree is empty; real recursive exit!!
{
ptr = pnew;
}
else if (Pnew->data < ptr->data)//Insert data is smaller than data at that location, insert to the left
{
Insert (Ptr->left); Recursive invocation
}
else//Insert data to the right when the data is greater than or equal to the location
{
Insert (ptr->right); Recursive invocation
}
}
Insert Successful


▲ Traverse:
void visit (bnode* ptr)// pointer to the node to be traversed, incoming root pointer on first call
{
if (ptr = = NULL) return; Recursive exit
Visit (Ptr->left); Recursive invocation, traversing left
cout << ptr->data << Endl; Output the contents of this node
Visit (ptr->right); Recursive invocation, traversing right
}
Traversal complete


▲ Empty the binary tree:
void Clear (bnode*& ptr)// pointer to the node to be emptied (a reference to the pointer must be used!!) ), the first call is passed to the root pointer
{
if (ptr = = NULL) return;
Clear (Ptr->left);
Clear (Ptr->right);
Delete ptr;
ptr = NULL;
}
Clear success


▲ Deleting a node (delete):
Deleting a node in a binary lookup tree is cumbersome, and there are two common methods: demotion and substitution

Downgrade method: Rime the left child of the deleted node into its right subtree below
Substitution method: Replaces the deleted node with the largest node in the left sub-tree of the removed electromechanical

Downgrade method implementation code:
void Deletenode (bnode*& ptr)//reference to the pointer of the node to be deleted!!
{
bnode* p = ptr; Save the address of the node first for later use
Insert (Ptr->left, ptr->right); Rime left child to right sub-tree (refer to insert function)
PTR = ptr->right;
Delete p; Delete the space of the node and use the p that saved the address just now, because PTR has changed
}
Delete Complete

The substitution method implements the code:
The function that finds the largest node below the left subtree is written first:
bnode*& Findmax (bnode*& ptr)//return type must be a reference!!!
{
if (ptr->right = = NULL) return ptr; Recursive exit
Findmax (Ptr->right);
}
void Deletenode (bnode*& ptr)
{
bnode* p = ptr;
bnode*& pmaxref = Findmax (ptr->left); Reference!!! must also be used here
bnode* Pmax = pmaxref; Save the address of the node pointed to by Pmaxref to Pmax
Pmaxref = NULL; Remove the largest node of the left subtree from the tree!! Note that the operation is a reference!!!
ptr = Pmax; Change the location of the node you want to delete to the left subtree max node; Notice that the PTR of the operation is a reference!!!
Pmax->left = p->left;
Pmax->right = p->right;
}
Delete Complete

▲ Modify a node (change): first delete and then insert

6. Algorithm (algorithm)
Algorithm analysis, efficiency, time complexity, space complexity
Large o notation (Big O Notation): Up to how many times
Algorithm design strategy: Brute force method, recursive method, greedy method, etc.
Find: Linear find, dichotomy lookup, index lookup
Sort by: Select sort, insert sort, bubble sort, quick sort, hill sort

Sort by: (in descending order, for example)

▲ Select Sort:
Idea: The first round of sorting puts the largest of all elements in the first, and then the next round sorts the largest remaining elements into the first one of the remaining elements, and then ...
Method: Double Loop or recursive

▲ Insert Sort:
Idea: think that the first element has been sequenced, and then see the next element, if the larger than the first row to its front, otherwise platoon behind, go down in turn ...
More complex to implement.

▲ Bubble Sort:
Idea: Each round only compare the size of adjacent elements, the former small after the large swap position, so that after more than one round, until no longer occur any exchange, sort end
The slowest Sort method

▲ Quick Sort:
Idea: Select a cutoff value (pivot), move greater than the cutoff value to the left, less than the cutoff value of the move to the right, you can generally use recursion
A variety of specific implementation methods

▲ Quick ordering in library functions: (#i nclude) (qsort)
Qsort (int*, length, sizeof (int), (*compare));
The parameter table is the first address of the array to be sorted, the length of the array, the element size of the array, the first address of the comparison function
The comparison function needs to be defined by itself

★ Custom templates and Standard template libraries

1. Custom templates
Templates are used for generic programming
Divided into function templates and class templates
When defining a template:
Template//templates header; TypeName keyword can be replaced by class
... {}//function body or class body, you can use the symbol t as a data type

When using templates:

Function templates can automatically identify types based on the type of incoming parameters
The class template needs to pass the parameters in angle brackets: vector vi;

2. Standard Template Library (STL)
The Standard Template Library contains the following content:
Container (Container)
Algorithm (algorithm)
Iterator (iterator)
Functor (pseudo function)
Adapter (Container adapter)
Allocator (dispenser)


3.container (Container)
For storing a series of data
Divided into sequence container and associative container two kinds
(Sequence container and associative container)

Common features of all containers:

There are three kinds of constructors (no parameters, no copies, no intervals)
Support operators: Assignment (=), Comparison (< <= > >= = =)
Swap function swap () is supported and two containers are exchanged (S1.swap (S2);)
Supported actions: INSERT, erase, clear, empty (judging non-empty), size
There are four types of iterators: iterator, Reverse_iterator, Const_iterator, Const_reverse_iterator
Iterator-related functions: Begin, end, Rbegin, rend


4.iterator (iterator)
An iterator is an inner class of a container that encapsulates only one pointer
External access to the elements of the container can be accessed through iterators, so the role of the iterator is the smart pointer
Operators that are overloaded internally by iterators typically have an asterisk (*), not equal to (! =), self-add (+ +), and auto Minus (--) four operators

The bridge of the iterator and its class is a number of iterator-related functions (begin,end,rbegin,rend), etc., with R being the inverse

How to use:

Class Name:: Iterator it; Declares an iterator object
For (It= object. Begin; It!= object. End; it++) {...}//to traverse a container


5.Sequence Container (Sequential container)
Includes three kinds: vector, deque, list

▲ The common features of sequential containers:
Constructors can specify number and initial values
Added resize (len) or resize (len, fillval)
Insert (position, NUM, data) added
Added assign (num, data)
Added the Kinsoku function: Front (), Back () (return reference)
Added add and subtract functions: push_back (data), Pop_back ()


▲vector: (#i nclude)
Vector is actually a dynamic array
Support [] (Do not check out of bounds)
Support at () (out of bounds throw exception)
Added capacity () function (capacity) (sometimes!=size ())
Added the reserve (LEN) function (adjust capacity)
High efficiency after plug-in


▲deque: (#i nclude)
Deque is actually an enhanced version of the vector.
Added pre-add and Subtract functions: Push_front (data), Pop_front ()
Capacity and reserve functions are reduced compared to vectors


▲list: (#i nclude)
List is actually a doubly linked list
[] and at () not supported
Supports only bidirectional iterators (+ +-) and does not support random iterators (+n-n)
Remove (data) added (delete all data nodes)
Added sort () (Ascending sort)
Added reverse () (reverse order)
Added unique () (removes adjacent repeating elements and becomes one)
Added merge (list2) (merge List2 order into current list,list2, merge back order)
Added splice (it, List2, List2.it1, List2.it2) (the interval in List2 is transferred to the specified position in the current list)
List applies when elements are frequently inserted and deleted


6.Associative Container (Associative container)
Includes two kinds: Map/multimap, Set/multiset

▲ the commonality of associative containers:
Two-fork search tree in essence
can be automatically sorted (requires that the container element's type must support the less-than operator)
Each element has a key value
Insert (data) added (no location required)
Added find (key) (returns the first; if not found, returns end ())
Added Erase (key) (delete all keys for key elements)
Added count (key)
Added Lower_bound (key), Upper_bound (key)
Added Equal_range (key)


▲map/multimap: (#i nclude


▲map/multimap Insert Element Method:
There are four ways to insert pairs:
Insert (Map::value_type ("ABC", 100));
Insert (Pair ("ABC", 100));
Insert (Make_pair ("ABC", 100));
["ABC"] = 100;
(Above "ABC" is key, 100 is value)
(Note: Value_type is a function inside the map Class)
(Note: Pair is a class template in the standard Template library whose elements are first, second)
(Note: Make_pair is a function in the standard library function)
(Note: The square bracket operator is used with caution: If "abc" does not exist, insert new; if "ABC" already exists, modify it in map, still insert new in Multimap)


▲set/multiset: (#i nclude)
Each element is made up of only one key
Set and Multiset differences: Ibid.

7.adapter (Container adapter)
#i nclude ==> Stack
#i nclude ==> Queue Pqueue

Use: Push (), pop, size (), Empty ()


8.algorithm (algorithm)
#i nclude ==> for_each find sort copy Replace
#i nclude ==> min Max accumulate swap

Basic C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.