The road to C++ promotion

Table of contents

1. The role of keywords

1.1 Commonly used keywords in the base class

1.1.1 const modification

1.1.2 virtual modification

1.1.3 static modification

1.1.4 friend modification

1.2 Common keywords for derived classes

1.2.1 explicit modification

1.2.2 template modification

1.2.3 noexcept modification

1.2.4 operator modification

1.2.5 override modification

2. Common grammar

2.1 References & Usage

3. C++ commonly used standard template library

3.1vector

3.1 Characteristics of vector container

3.2 Access to elements in the vector container

3.3vector commonly used functions

3.4 Four ways of vector initialization

3.2string

3.3queue和priority_queue

3.3.1 tail

3.3.2priority_queue

3.4map

3.5set

3.6stack

3.7pair

3.8 algorithm

4. 23 design patterns of C++


1. The role of keywords

1.1 Commonly used keywords in the base class

1.1.1 const modification

1. Member functions modified by const
1. Adding const after a member function is called a constant function;
2. A constant function cannot modify a member variable;
3. After adding mutable before a member variable, it can be modified in a constant function.

2. Constant objects
1. Objects with const added before declaring objects are called constant objects;
2. Constant objects can only call constant functions.

Refer to C++'s const modified member function_const modified function_Programmer's blog with both software and hardware-CSDN blog

Sample code:

int width() const { return metric(PdmWidth); }

1.1.2 virtual modification

A virtual function refers to a member function in a class that you want to overload. When you use a base class pointer or reference to point to an inherited class object, when calling a virtual function, the version of the inherited class is actually called. ——Excerpt from MSDN

Sample code:

virtual int devType() const;

1.1.3 static modification

  • (1) Non-static members cannot be called in static member functions.
  • (2) Static members can be called in non-static member functions. Because static members belong to the class itself and exist before the object of the class is generated, static members can be called in non-static member functions.
  • (3) Static member variables must be initialized before use (such as int MyClass::m_nNumber = 0;), otherwise an error will occur during linker.

General summary : In a class, static can be used to modify static data members and static member methods.

static data member

  • (1) Static data members can realize data sharing between multiple objects. It is a shared member of all objects of a class. It only occupies one space in memory. If its value is changed, this data member in each object values ​​are changed.
  • (2) Static data members are allocated space when the program starts running, and are released after the program ends. As long as static data members are specified in the class, even if no object is defined, space will be allocated for static data members.
  • (3) Static data members can be initialized, but only outside the class. If no initial value is assigned to the static data member, the compiler will automatically initialize it to 0.
  • (4) Static data members can be referenced either by object name or by class name.

static member function

  • (1) Static member functions are the same as static data members, they all belong to the static members of the class, not object members.
  • (2) Non-static member functions have this pointer, while static member functions do not have this pointer.
  • (3) Static member functions are mainly used to locate static data members and cannot access non-static members.

Sample code:

static inline qreal devicePixelRatioFScale() { return 0x10000; }

1.1.4 friend modification

The friend mechanism in C++ allows non-public members of a class to be accessed by a class or function. Friends are divided into three types according to types: ordinary non-class member functions as friends, class member functions as friends, and classes as friends. Friend includes the declaration of friend and the definition of friend. The declaration of a friend is extern by default, which means that the scope of a friend class or friend function has been extended to include the scope defined by the class, so it doesn't matter even if we define a friend function inside the class.

Sample code:

friend class QPainter;

1.2 Common keywords for derived classes

1.2.1 explicit modification

First of all, the explicit keyword in C++ can only be used to modify a class constructor with only one parameter. Its function is to indicate that the constructor is explicit, not implicit. Another keyword corresponding to it is implicit , meaning hidden, the class constructor is declared as implicit by default.

Modification with explicit can prevent the default implicit conversion.

Reference: Detailed explanation of explicit in C++_c++ explicit_Yang Jian's Blog-CSDN Blog

Sample code:

explicit QMainWindow(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags());

1.2.2 template modification

1. Function template

template< class formal parameter name, class formal parameter name, ... > return type function name (parameter list) { function body }

For example: template <class T> void swap(T& a,T& b){}

When such a template function is called, the type T is replaced by the type at the time of the call. If swap(a, b), a and b are both int types, then the formal parameter T in the template function swap will be replaced by int, and the template function will become swap(int &a, int &b). And when swap(a,b), a and b are both double types, then the formal parameter T in the template function swap will be replaced by double, and the template function will become swap(double &a, double &b), so if The value of the exchange variable in our program is no longer limited by type.

Two, class template

template< class formal parameter name, class formal parameter name, ...> class class name{...};

For example: template <class T> class A { public: T a; T b; T hy(T c, T &d); };

Two member variables a and b of type T are declared in class A, and a function hy with return type T and two parameters of type T is declared.

Sample code:

template <> inline QWidget *qobject_cast<QWidget*>(QObject *o)

{

    if (!o || !o->isWidgetType()) return nullptr;

    return static_cast<QWidget*>(o);

}

1.2.3 noexcept modification

noexcept is a keyword introduced by C++11 to indicate whether a function or expression will throw an exception during execution. It can be declared as part of a function or used as part of an expression.

1. Features:

  1. Improve code efficiency : If a function uses a noexcept statement, the compiler will think that this function will not throw an exception, so that some optimizations can be performed on this function, such as avoiding additional stack operations and exception handling code, etc., thereby improving code efficiency.

  2. Help programmers debug : If a function is not declared with noexcept and an exception is thrown inside the function, the exception will be passed on the function call stack until it is caught. If it is not caught, the program will crash. And if the noexcept statement is used, once an exception is thrown inside the function, the program will directly call the std::terminate() function to terminate the program, which can help programmers quickly discover and debug abnormal problems in the program.

  3. Helps in writing high-quality code : Using the noexcept declaration can help in writing high-quality code, because it can explicitly indicate whether a function will throw an exception, making it easier for the caller of the function to handle the abnormal situation correctly.

Reference: noexcept syntax analysis_LiuZuqiang_3027's Blog-CSDN Blog

Sample code:

    inline QByteArray() noexcept;

1.2.4 operator modification

operator is a keyword of C++. It is used together with an operator (such as =) to indicate an operator overloading function. When understanding, operator and operator (such as operator=) can be regarded as a function name .

Using operator to overload operators is a way to extend the functions of operators in C++. The reasons for using operator extension operator functionality are as follows:

Make the use of the operator after overloading consistent with that before overloading.
The function of the expansion operator can only be realized by means of functions (in fact, various "functions" in C++ are realized by functions)

Sample code:

    Q_REQUIRED_RESULT inline QByteRef operator[](uint i);

1.2.5 override modification

If a derived class uses the override descriptor when declaring a virtual function, the function must override the function with the same name in its base class, otherwise the code will fail to compile.

Reference: C++ override keyword usage_xiaoheibaqi's blog-CSDN blog

Sample code:

    bool open(OpenMode mode) override;

2. Common grammar

2.1 References & Usage

Just declare the function as a reference, and pass by reference when you don't need to pass parameters.

Sample code:


#include <iostream>
void plus(int &n){
    n = n + 1;
}
void plus1(int n){
    n = n+1;
}
int main(int argc, const char * argv[]) {
    // insert code here...
    int a = 10, b = 10;
    plus(a);
    plus1(b);
    printf("a = %d \nb = %d \n",a,b);
}
最后输出: a = 11

b = 10

3. C++ commonly used standard template library

#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<iterator>
#include<vector>
#include<list>
#include<queue>
#include<stack>
#include<set>
#include<bitset>
#include<map>
using namespace std;

3.1vector

3.1 Characteristics of vector container

In C language, we often worry about the size of the array . At this time, vector can solve the situation that the array is out of bounds.

Vector is a vector. We call it an "indefinite length array". Its length will automatically change according to needs. In addition, vector can also be used to store graphs in the form of adjacency linked lists. In addition, Vector needs to be declared #include<vector>andusing namespace std;

vector<typename> name;

  • Methods for defining Vector arrays
    vector<typename> arrayname[arraysize];

3.2 Access to elements in the vector container

Vector generally has two access methods:

  • Access by subscript:
    Same as ordinary array access!
  • Access through an iterator:
    It can be understood as access through a pointer, which is defined as: vector<int>::iterator it;In this way, we have defined an iterator (iterator) it, and can access the elements in the vector through *it. for example:
vector<int>vi;
for(vector<int>::iterator it = vi.begin();it != vi.end;it++)
{
	printf("%d",*it);
}//vi是已经定义好的一个数组

3.3vector commonly used functions

  • begin();Get the address of the first element of the vector. example:for(vector<int>::iterator it = vi.begin();it != vi.end;it++)
  • end();Get the address of the last element of the vector. Example: Same as above
    Note : The vector iterator does not support it < vi.end()the writing method, so it can only be usedit != vi.end()
  • push_back(x)Add an element x after the vector Example:vi.push_back(x);
  • pop.back();Remove the tail element of vector. example:vi.pop.back();
  • size();Get the number of elements in the vector. example:vi.size();
  • clear();Clear all elements in vector. example:vi.clear();
  • insert(it,x);Inserts an element x at any iterator it in vector. example: vi.insert(vi.begin()+2,-1);//再数组vi第二个元素后插入-1
  • erase();erase() has two usages: 1. erase(it);Delete the element where the iterator is it
    2. erase(first,last)Delete the element in the range [first, last).

3.4 Four ways of vector initialization

	void ceshi(vector<int> v)
   {
		for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
		{
			cout << *it << endl;
		}

	}
	//四种方式 1
	vector<int > v;
	int arr[] = { 1,2,3,4,5,6 };
	//2 最常用
	vector<int> v1(arr,arr+sizeof(arr)/sizeof(int));
	//3
	vector<int> v2(v1.begin(), v1.end());
	//4
	vector<int> v3(v2);
	ceshi(v1);
	ceshi(v2);
	ceshi(v3);

Other detailed references: [STL] Vertor basic usage explanation + code examples_Windalove's Blog-CSDN Blog

3.2string

1. string(const char *s) : initialize the string object to the string pointed to by s

string str("hello");

2. string(size_type n,char c) : Create a string object containing n elements, each of which is initialized to the character c

string str(10, 'a');

3. string(const string &str) : Initialize a string object to a string object str (copy constructor)

string str("abcde");
string str2(str);

4. string() : Create a default string object with a length of 0 (default constructor)

string str;

5. Use C language style strings to process string objects

string str = "hello!";

6. Obtain the length of the string object. In C language, use strlen() to obtain the length of the string. In C++, use str.size()or str.length().

string str("hello!");
int len1 = str.size();
int len2 = str.length();

7. Assign a string object to another string object

string str("hello!");
string str2;
str2 = str;

8. Stitching of string objects
In C language, strcat and strncat functions are used to perform string splicing operations. In C++, the following methods can be used:

string str1("hello");
string str2("world");
string str3 = str1 + str2;

9. Use += to append a string object, characters, and C-style strings to a string object

string str("hello");
string str2("world");
str += str2;
str += 'a';
str += "abcd";

10. string.append() function, add a string object or c-style string after the string object.

string str("hello");
string str2("world");
str.append(str2);
str.append("abcd");

11. string.push_back() function to append a character after a string object

string str("hello");
char ch = 'a';
str.push_back(ch);

12. For the comparison of string objects, relational operators can be used directly.

string str1("abcd");
string str2("abcd");
if(str1 == str2)
	break;

13. The comparison of string objects can also use the string.compare() method

int compare(const string&str) const;
int compare(size_t pos,size_t len,const string&str)const;
int compare(size_t pos,size_t len,const string&str, size_t subpos,size_t sublen)const;
int compare(const char * s)const;
int compare(size_t pos,size_t len,const char * s)const;
int compare(size_t pos,size_t len,const char * s,size_t n)const;

// example
string str1("hello world");
string str2("hello boy");
str1.compare(6, 3, str2, 6, 3);

14. Use the string.substr() function to get substrings

string str("hello");
string str2 = str.substr(3,2)

15. Access the elements of the string string

string str("hello");
cout << str[2] << endl;
cout << str.at(2) << endl;

16. Use  string.find() method to find characters

//  从字符串的 pos 位置开始(若不指定 pos 的值,则默认从索引 0 处开始),查找子字符串 str。
//  如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回 string::npos:
//  string 类将 npos 定义为保证大于任何有效下标的值。
size_type find (const string& str, size_type pos = 0) const;
size_type find (const char *s, size_type pos = 0) const;
size_type find (const char *s, size_type pos, size_type n);
size_type find (char ch, size_type pos = 0) const;

17. string.rfind() Similar to the string.find() method, except that the search order is different, string.rfind() searches forward from the specified position pos (the default is the end of the string) until the beginning of the string, and returns the first time The index of the first character of the match when a match was found. In other words, find the last occurrence of a substring or character.

18. string.find_first_of() The method searches backwards from the specified position in the string (the default is index 0) to find the position where any character in the parameter appears for the first time

string str("hello world");
int pos = str.find_first_of("abcde");
int pos = str.find_first_of("abcde", 1);  // 第二个参数为位置

19. string.find_last_of() The method finds the last occurrence of any character in the parameter in the string

20. string.find_first_not_of() The method finds the first character in the string that is not included in the parameter

21. string.find_last_not_of() The method finds the last character in the string that is not included in the parameter

22. Use  string.insert() the insert operation

string& insert(size_t pos,const string&str);   
// 在位置 pos 处插入字符串 str

string& insert(size_t pos,const string&str,size_t subpos,size_t sublen); 
// 在位置 pos 处插入字符串 str 的从位置 subpos 处开始的 sublen 个字符

string& insert(size_t pos,const char * s);    
// 在位置 pos 处插入字符串 s

string& insert(size_t pos,const char * s,size_t n); 
// 在位置 pos 处插入字符串 s 的前 n 个字符

string& insert(size_t pos,size_t n,char c);      
// 在位置 pos 处插入 n 个字符 c

iterator insert (const_iterator p, size_t n, char c); 
// 在 p 处插入 n 个字符 c,并返回插入后迭代器的位置

iterator insert (const_iterator p, char c);       
// 在 p 处插入字符 c,并返回插入后迭代器的位置

23. Use string.erase() to delete elements

string& erase (size_t pos = 0, size_t len = npos);   // 删除从 pos 处开始的 n 个字符
iterator erase (const_iterator p);            // 删除 p 处的一个字符,并返回删除后迭代器的位置
iterator erase (const_iterator first, const_iterator last); // 删除从 first 到last 之间的字符,并返回删除后迭代器的位置

24. Use the getline() function to get string input

string str;
getline(cin, str);

25. Use the string.empty() function to determine whether the string is empty

26. Use the string.swap() function to swap two strings

string str1 = "hello";
string str2 = "HELLO";
str1.swap(str2);

27. string.back()Get or modify the last character of a string

string str("abcd");
char b = str.back();
str.back() = 'e';

28. string.front()Get or modify the first character of a string

29. string.pop_back()Delete the last element of the string

3.3queue和priority_queue

3.3.1 tail

Queue is a queue. In STL , a first-in-first-out container is implemented. To use queue, you need to add the queue header file.

The definition of queue, queue< typename > q; where typename can be any type or container.

For queue access, since the queue is a first-in-first-out restrictive data structure, in STL, the first element of the queue can only be accessed through front(), or the tail element of the queue can be accessed through back().

        queue<`int`> q ;
    for(int i=1;i<5;i++){
        q.push(i) ;
    }
    cout << q.front() << endl ;
    cout << q.back() << endl ;
    输出结果:1
4

Queue commonly used functions
(1) push(), push(x) put x into the queue, time complexity O(1)
(2) front(), access the first element of the queue, back() access the tail element of the queue, time complexity O (1).
(3) pop(), the first element of the team is dequeued, and the time complexity is O(1).

queue<int> q ;
    for(int i=1;i<5;i++){         q.push(i) ;     }     q.pop() ;     cout << q.front() << endl ;     cout << q .back() << endl ; Output result: 2 4 (4) empty(), judge whether the queue is empty, if it is empty, return true, otherwise return false. (5) size(), returns the number of elements in the queue, and the time complexity is O(1).








    queue<int> q ;
    for(int i=1;i<5;i++){
        q.push(i) ;
    }
    if(!q.empty()){
        cout << q.size() ;
    }
输出结果:4

Common uses of Queue:
    When you need to implement breadth-first search, you don't need to manually implement a queue yourself. Before using the front() and pop() functions, you must use empty() to determine whether the queue is empty, otherwise an error may occur because the queue is empty.

3.3.2priority_queue

priority_queue is also known as priority queue, and its underlying layer is implemented with a heap. In a priority queue, the element at the head of the queue must be the one with the highest priority in the current queue. The heap in C++ defaults to the big heap.

The definition of priority_queue, priority_queue<typename> q, typename can be any type of element. To use the priority queue, the header file #include[HTML_REMOVED] should be added first.
Priority_queue can only access the first element of the team (the top element of the heap), which is the element with the highest priority, through the top() function.

priority_queue<int> q ;
    q.push(3) ;
    q.push(1) ;
    q.push(5) ;
    cout << q.top() << endl ;
output: 5

Priority_queue common functions
(1) push(x), time complexity O(logN), N is the number of elements in the heap.
(2) top(), top() can get the first element of the team, the time complexity is O(1)
(3) pop(), the top element of the heap is dequeued, the time complexity is O(logN), where N is in the heap the number of elements.

priority_queue<int> q ;
    q.push(3) ;
    q.push(1) ;
    q.push(5) ;
    cout << q.top() << endl ;
    q.pop() ;
    cout << q.top() << endl ;
输出结果:5
3

(4) empty(), to determine whether the queue is empty, return true if it is empty, otherwise return false.
(5) size(), returns the number of elements in the priority queue, time complexity O(1)

priority_queue<int> q ;
    q.push(3) ;
    q.push(1) ;
    q.push(5) ;
    if(!q.empty()){
        cout << q.size() << endl ;
    }
输出结果:3

3.4map

Map is translated into mapping, and map can map any basic type (including STL containers) to any basic class. (including STL containers). If you want to use map, you need to add a map header file , and add "using namespace std" under the header file, so that you can use map in your code.


The definition of map, map[HTML_REMOVED] mp; the definition of map is a little different from other STL containers, because map needs to determine the type before mapping (key key) and the type after mapping (value value), and the data type stored in map is a pair of KV structured data. If the map is a mapping of strings to integers, strings must be used instead of char arrays.
Map access, map generally has two access methods, through "subscript" access or through iterator access.


(1) Access by "subscript" is the same as that of ordinary arrays. For example, if you define a map[HTML_REMOVED] mp;, you can use mp["hello"] = 8 to add data to the map, and use mp["hello"] to access the value whose key is "hello" in the map. The keys in the map are unique, you can observe the output of the code below.
unordered_map<string,int> um ;
    um["hello"] = 8 ;
    um["hello"] = 100 ;
    cout << um["hello"] << endl ;
output: 100
(2) access via iterator, A little different from other STL iterators, since the data type of the map is a KV structure, the iterator contains the data of these two aspects. The map iterator is defined as map[HTML_REMOVED]::iterator it; the key can be accessed through it->first, and the value can be accessed through it->second. Observe the code below,

map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    for(map<string, int>::iterator it=mp.begin();it!=mp.end();it++){         cout << it->first << ' ' << it->second << endl ;     } output result: aloha 666 good 777 hello 100     Observing the output results, it is very interesting that the map is sorted according to the key value from small to large, and if it is a string, it is sorted according to lexicographical order. The map is implemented using a red-black tree.






    Commonly used functions of map:
(1) find (key), returns the iterator of the mapping whose key is key, the time complexity is O(logN), and N is the number of mappings in the map.

map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    auto it = mp.find ("good") ;
    cout << it->first << ' ' << it->second << endl ;
output result: good 777
(2) erase(), erase() has two usages: delete a single element and delete elements within a range.
a. There are two ways to delete a single element,
mp.erase(it), it is the iterator of the element to be deleted, and the time complexity is O(1).

map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    mp.erase(mp. find("good"));
    for(auto ele : mp){         cout << ele.first << ' ' << ele.second << endl ;     } output: aloha 666 hello 100 mp.erase(key), key is the key of the mapping to be deleted. Time complexity O(logN). N is the number of elements in the map.




map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    mp.erase("good");
    for(auto ele : mp){
        cout << ele.first << ' ' << ele.second << endl ;
    }

Output result: aloha 666
hello 100
            b. To delete elements in a range, you can only use an iterator to delete, erase(st, ed), means to delete elements in the range [st, ed).
map<string,int> mp ;
mp["hello"] = 8 ;
mp["hello"] = 100 ;
mp["aloha"] = 666 ;
mp["good"] = 777 ;
mp.erase(mp. find("good"),mp.find("hello"));
for(auto ele : mp){ cout << ele.first << ' ' << ele.second << endl ; } output result: aloha 666 Note for hello 100         , the iterator position of st must be before ed. map<string,












        cout << ele.first << ' ' << ele.second << endl ;
    }

        Output result: aloha 666
good 777
hello 100
In fact, nothing is deleted.

(3) size(), used to obtain the logarithm mapped in the map, time complexity O(1).

map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    cout << mp.size() << endl ;
输出结果:3

(4) clear(), used to clear all elements in the map, the complexity is O(N), where N is the number of elements in the map.

map<string,int> mp ;
    mp["hello"] = 8 ;
    mp["hello"] = 100 ;
    mp["aloha"] = 666 ;
    mp["good"] = 777 ;
    mp.clear() ;
    cout << mp.size() << endl ; 
输出结果:0
   

Common uses of map:
(1) For questions that need to establish a mapping between characters (or strings) and integers, using map can reduce the amount of code.
(2) For the problem of judging the existence of large integers or other types of data, map can be used as a bool array.
(3) Mapping between strings and strings.
Supplement: map, key and value are unique, and if a key needs to correspond to multiple values, only multimap can be used. In addition, unordered_map is added to the C++11 standard, which replaces the red-black tree implementation inside the map with hash, so that it can be used to process mapping without the need to sort by key, and the speed is much faster than map.

3.5set

(1) set: Translated as a collection, it is a container that is automatically ordered internally and does not contain repeated elements.

Function: Automatically deduplicate and sort in ascending order

(2) Prerequisite: add set header file

#include<set>
using namespace std;

(3) Definition

set<typename> name;
set<typename> Arrayname[arraySize];

(4) Access (only through iterator = pointer access)

set<typename>::iterator it;//定义迭代器it

Since STL containers other than vector and string do not support the *(it+i) access method, they can only be enumerated as follows:

#include<cstdio>
#include<set>
using namespace std;
int main(){
	set<int> st;
	st.insert(3);
	st.insert(5);
	st.insert(2);
	st.insert(3);
	for(set<int>::iterator it = st.begin(); it != st.emd(); it++){
	printf("%d",*it);//输出结果:2 3 5
	}
	return 0;
}

(5) Commonly used functions

function

Function

begin()

first element address

end()

The next address of the tail element address (Americans are more accustomed to left-closed and right-opened)

size()

number of elements

clear()

empty element

insert(x)

insert element

find(x)

Find an element and return an iterator (pointer) to the corresponding element

erase(it)

Delete the element at the specified position, which can be used in conjunction with the find function. st. erase(st. find(x));

erase(x)

Delete element x, equivalent to st.erase(st.find(x));

erase(first,last)

Delete all elements within [ first , last )

3.6stack

(1) stack: translated as a stack, a last-in-first-out container.

It is used to simulate some recursion to prevent the program's limitation of stack memory from causing program errors.

(2) Prerequisite: add stack header file

#include<stack>
using namespace std;

(3) Definition

stack<typename> name;

(4) Access

The top element of the stack can only be accessed through top()

(5) Commonly used functions

function

Function

size()

number of elements

empty()

Check if it is empty, return bool

push(x)

stack

top()

Get the top element of the stack

pop()

Pop the top element of the stack

3.7pair

(1) pair: In fact, it can be regarded as a structure with two elements inside

Common use 1: instead of a binary structure, saving coding time
Common use 2: insert as a key-value pair of a map

#include<string>
#include<map>
int main(){
	map<string,int> mp;
	mp.insert(make_pair("hehe",5));
	mp.insert(pair<string,int>("hehe",5));
	for(map<string,int>::iterator it = mp.begin(); it != mp.end(); it++){
		printf("%c %d\n",it->first,it->second);
	}
}

(2) Prerequisite: add utility header file or map header file

The internal implementation of map involves pair, so the utility header file is automatically added when the map header file is added

#include<map>
//或 #include<utility> 
using namespace std;

(3) Definition

//定义
pair<typename1,typename2> name;
//定义并初始化
pair<string,int> p("haha",5);
//临时变量(只用一次的)
pair<string,int>("haha",5)
make_pair("haha",5)

(4) Access

There are only two elements in the pair, which are first and second, and they only need to be accessed in the way of a normal structure.

(5) Commonly used functions

function

Function

comparison operator

The comparison rule is to first use the size of first as the standard, and then judge the size of second when they are equal

3.8 algorithm

function

Function

max(x,y)

Maximum value (both int and double are acceptable)

max(x,max(y,z))

maximum of three numbers

min(x,y)

minimum value

abs(int x)

Absolute value (Note: Please use fabs in math for the absolute value of floating-point type)

swap(x,y)

exchange

reverse(it,it2)

Reverse the elements of the array pointer or container iterator in the range [it,it2)

next_permutation(it,it2)

gives the next sequence of a sequence in the full permutation

fill(it,it2,value)

Assign the same value to a range of an array or container

sort(it,it2)

to sort

sort(it,it2,cmp)

to sort

lower_bound(it,it2,val)

Find the position of the first element whose value is greater than or equal to val in the [it, it2) range of the array or container, and return a pointer or iterator, if not, return a pointer or iterator that can insert the element

upper_bound(it,it2,val)

Find the position of the first element whose value is greater than val in the range [it,it2) of the array or container, and return a pointer or iterator, or return a pointer or iterator that can insert the element if it does not exist

4. 23 design patterns of C++

reference

C++ design pattern (all 23 types) - momohola's blog - CSDN blog

 1. Creational mode
Factory mode (factory mode)
AbstactFactory mode (abstract factory mode)
Singleton mode (singleton mode)
Builder mode (builder mode)
Prototype mode (prototype mode)
2. Structural mode
Bridge mode (bridge mode)
Adapter Mode (adapter mode)
Decorator mode (decorator mode)
Composite mode (combined entity mode)
Flyweight mode (flyweight mode)
Facade mode (appearance mode)
Proxy mode (proxy mode)
3. Behavior mode
Template mode (template mode)
Strategy mode (Strategy Mode)
State Mode (State Mode)
Observer Mode (Observer Mode)
Memento Mode (Memorandum Mode)
Mediator Mode (Intermediary Mode)
Command Mode (Command Mode)
Visitor Mode (Visitor Mode)
Chain of Responsibility Mode (Chain of Responsibility mode)
Iterator mode (iterator mode)
Interpreter mode (interpreter mode)

Guess you like

Origin blog.csdn.net/weixin_51248645/article/details/130959127