The most detailed introduction to the c++ STL library (nanny level teaching)

Table of contents

I'm here to write an article again for the rc car in the pit ヾ(≧▽≦*)o

First, let's figure out what the STL library is

One. Quick sort (Sort):

1. Basic usage of Sort:

2. Sort advanced usage (CMP):

3.Sort sorts the structure (or class):

Two.Map

Introduction to Map:

definition:

Take a chestnut:

Quiz time!

 Topic: Discretization Fundamentals

input format

output format

Input/Output Example 1

answer:

Three.stack(stack)

Introduction to the stack:

Definition of stack:

Member functions of the stack:

Four. Binary search

Nice function:

1.lower_bound function

2.upper_bound function

3.binary_search: Find whether an element appears in the array.

Another question!

​ 

Title: Array Line Segments and M

input format

output format

Input/Output Example 1

answer:

Six.list(linked list)

Common operation functions:

definition of list

ヽ( ̄ω ̄( ̄ω ̄〃)ゝ That’s it for today, see you soon!


 

 

 

I'm here to write an article again for the rc car in the pit ヾ(≧▽≦*)o

Those who want to "deep discussion" can add me qq28562939

Presumably, people who often engage in C++ have probably heard of the STL library (it happens to be researching recently), and the most famous one is ours-sort quick sort!

It's okay for brothers who don't know,

Let's continue reading.

971a71db51780b6ae7e37c02d9491cba.png

 The difficulty increases step by step.

 

First, let's figure out what the STL library is

STL, the scientific name Standard Template Library, generally we call it the Standard Template Library, is a collective name for a series of software.

Fundamentally speaking, STL is a collection of "containers". These "containers" include list, vector, set, and map.

A collection of methods and some other components. For example, the sort function in <algorithm> and the string class in <string> are both

Is the content of STL.

There are many other contents in the STL library, such as: vector (vector), stack (stack), queue (queue), priority queue

(priority_queue), linked list (list), collection (set), mapping (map) and other containers; min, max, swap

, sort, lower_bound, upper_bound and other algorithms, some of which are even unknown. ㄟ( ▔, ▔ )ㄏ


One. Quick sort (Sort):

As we all know, c++ has a variety of normal sorting and weird sorting, such as bubble sorting, the time complexity is N(O^2), which is outrageous

Is it right? Arranging an array of 100,000 elements will time out.

39fde83e8ab951081df3bfad24aca8bd.png

 

Therefore, we will not use bubbling in the future, and use sort to quickly sort (abandon the dark and turn to the bright), the time complexity is N*LogN, and it will not exceed 1 second to sort a million numbers.

1. Basic usage of Sort:

sort is a system function that comes with STL, and its format is:

void sort(start address of elements to be sorted, end address of elements to be sorted, comparison function);

The comparison function can be omitted here, it is sorted from small to large by default (ascending sort)

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
	int a[]={3,5,2,6,9,3,5};
	sort(a,a+7);//7是数组的元素个数,这里a为数组的开头,a+7就等于排序到数组的第七个元素
	for(int i=0;i<6;i++)
		cout<<a[i]<<" ";
}

output:

2 3 3 5 5 6

2. Sort advanced usage (CMP):

void sort (the start address of the elements to be sorted, the end address of the elements to be sorted, comparison function);, yes, it is him again, here we send

There is still a comparison function that is not mentioned. The function of this comparison function is to customize the sorting method, such as descending sorting.

Definition: bool cmp(int x, int y)...., if it returns True then x will be in front of y.

#include<algorithm>
#include<iostream>
using namespace std;
bool cmp(int x,int y)
{
	if(x>y)return true;//降序
	return false;
}
int main()
{
	int a[]={3,5,2,6,9,3,5};
	sort(a,a+7,cmp);//7是数组的元素个数
	for(int i=0;i<6;i++)
		cout<<a[i]<<" ";
}

output:

9 6 5 5 3 3

3.Sort sorts the structure (or class):

The students had a rice cooking competition. The participating team members were "Crazy Zhang San", "Old Ba the Cooker" and Wang Wu. Whoever ate more would be ranked higher. If they ate the same amount, whoever ate Whoever has more hamburgers will be ranked higher:

#include<algorithm>
#include<iostream>
using namespace std;
struct ganfan
{
	string name;
	int zongshu;
	int hanbao;
};
bool cmp(ganfan x,ganfan y)
{
	if(x.zongshu>y.zongshu)return true;
	else if(x.hanbao>y.hanbao&&x.zongshu==y.zongshu)//如果一样多那么比谁吃的汉堡多
	return false;
}
int main()
{
	ganfan a[3];
	a[0].name="zhangsan";a[0].zongshu=200;a[0].hanbao=6;
	a[1].name="laoba";a[1].zongshu=170;a[1].hanbao=13;
	a[2].name="wangwu";a[2].zongshu=170;a[2].hanbao=10;
	sort(a,a+3,cmp);
	for(int i=0;i<3;i++)
		cout<<a[i].name<<" ";
}

output:

wangwu laoba zhangsan

We can see that Zhang San has the most dry rice, so he ranks at the top. Lao Ba and Wang Wu have the same amount of dried rice, but Lao Ba eats more hamburgers, so Lao Ba ranks in front of Wang Wu.

Two.Map

Introduction to Map:

A map is an associative container of the STL that provides one-to-one hashing .

  • The first one can be called a keyword (key), and each keyword can only appear once in the map;
  • The second may be called the value of the keyword;

definition:

map<类型,类型> m;

Take a chestnut:

Record the corresponding hobbies of each person's name, Zhang San likes to eat hamburgers:

#include<map>
#include<iostream>
using namespace std;
int main()
{
	map<string,string> m;
	m["张三"]="吃汉堡";
	cout<<"张三: "<<m["张三"]; 
}

 output:

张三: 吃汉堡

 

Quiz time!

df2b8fc98dbf62e1e2f5863a43a8ecfc.png

 Topic: Discretization Fundamentals

When programming using the discretization method, it is usually necessary to know the number (rank value) of each number after sorting, and the same number corresponds to the same number.

input format

 

Line 1: An integer N. 1<=N<=100000.
Line 2: There are N integers, and each number is int range. Note: There may be identical integers.

 

output format

 

Output the rank of each number in turn.

 

Input/Output Example 1

enter:

5
8 2 6 9 2

output:

3 1 2 4 1

answer:

This problem can be easily solved with Sort and Map:

#include<bits/stdc++.h>
using namespace std;
int N,a[100001],b[100001];
map<int,int> m;
int main(){
    
    cin>>N;
    for(int i=0;i<N;i++)
    {
        cin>>a[i];
        b[i]=a[i];
    }
    sort(b,b+N);//将数组排序
    int c=1;//排名
    m[b[0]]=1;//因为数组经过排序,所以第1个元素肯定是第一
    for(int i=1;i<N;i++)
    {
        if(b[i]!=b[i-1])//判断是否不与前一个数相等
        {
            c++;
            m[b[i]]=c;
        }
    }
    for(int i=0;i<N;i++)
        if(m[a[i]]!=0)
            cout<<m[a[i]]<<" ";//按照原来的下标输出
    
    return 0;
}

Three.stack(stack)

head File:

#include<stack>

Stack seems to have a translation called "salted fish"... Hehe.

Introduction to the stack:

A stack is like a box, elements can be put in or removed, but everyone knows that if you want to take out the things under the box, you must first take out the things above him.

If we push 1, 2, 3, 4, and 5 into the stack in order :

04c131ebc812f96f01151e3a54b8f13c.png

                                                                                                                         ——Beautiful hand-painted by the blogger 

Definition of stack:

stack<类型(可以不写)> st;
或者stack st;

Very easy, isn't it?

Member functions of the stack:

.empty() Determine whether the stack is empty, return true if it is empty
.pop() Remove the top element of the stack
.push(what what what) Add an element to the top of the stack
.size() Returns the number of elements in the stack
.top() Return the top element of the stack

.empty() Determines whether the stack is empty.

stack st;
if(st.empty())//如果是空那么执行下面代码
    ......

 .push(what what what), add elements to the top of the stack.

.top(), return the top element of the stack, remember to return, to be output separately.

#include<stack>
#include<iostream>
using namespace std;
stack<int> st;
int main(){
    
    st.push(5418);
    cout<<st.top();//输出栈顶元素
    return 0;
}

Output 5418. 

                                                    


.size(), returns the number of elements in the stack.

#include<stack>
#include<iostream>
using namespace std;
stack<int> st;
int main(){
    
    st.push(5418);
    cout<<st.size();
    
    return 0;
}

output 1 


.pop(), remove the top element of the stack:

#include<stack>
#include<iostream>
using namespace std;
stack<int> st;
int main(){
    
    st.push(1452);
    st.push(5418);
    st.pop();
    cout<<st.top();
    
    return 0;
}

 Output 1452.

 

Simple isn't it?


Four. Binary search

head File:

#include <algorithm>

Nice function:

1.lower_bound function

For ordered containers, ordered containers, ordered containers (the important thing is said three times) fast binary search finds the first one greater than or equal to

The position (subscript) of the specified number, if not found, returns the position after the last data.

  For arrays, the usual format is:

The subscript of the array to be searched = lower_bound (the start position of the array to be searched, the end position of the array to be searched, the number to be found) – the start position of the array (generally write the array name);

for example:

#include<algorithm>
#include<iostream>

using namespace std;

int main() {

    int a[5] = { 1,2,3,3,8 };

    //从 a 数组中找到第一个不小于   3 的元素

    int   index = lower_bound(a, a + 5, 3)-a;//查找的数组下标 = lower_bound(数组要查找的开始位置,数组要查找的结束位置后面,要找的数) – 数组开始位置;

    if   (index==5 ) cout << " not found! ";//index=5,也就是数组末尾的位置。
    else  cout << index;

    return   0;

}

 output 2.

2.upper_bound function

There is a function upper_bound similar to lower_bound, fast binary search to find the first position greater than the specified number (below

mark), if not found, returns the position after the last data.

Take chestnuts, ah... there are almost no chestnuts. (っ°Д °;)っ

#include<algorithm>
#include<iostream>

using namespace std;

int main() {

    int a[5] = { 1,2,3,3,8 };
    //从 a 数组中找到第一个大于 3 的元素

    int   index = upper_bound(a, a + 5, 3)-a;

    if   (index==5 ) cout << " not found! ";
    else cout << index;

    return   0;

}

 output 4.

3.binary_search: Find whether an element appears in the array.

void binary_search (the first address of the array, the end address, the number to be searched)

The return value is bool type, and return true if found.

 

 

Another question!

41392fe6aaffa9f5bc56fbe02133c7d1.png 

Title: Array Line Segments and M

input format

 

  The first line contains 2 positive integers N and M, the range of N is [1, 1000000], and the range of M is [1, 10^9].

  The second line is N positive integers, and each number ranges from [1, 1000].

 

 

output format

 

  an integer.

 

Input/Output Example 1

enter:

10 20

1 7 10 10 7 10 6 4 6 6

 

output:

2

answer:

I used the method of prefix sum to solve this question, because there are more data, so it is faster, and it can also become an ordered sequence.

The code is a little bit difficult, let's figure it out:

#include<bits/stdc++.h>
using namespace std;
int N,M;
int a[1000001];
int main(){
    
    cin>>N>>M;
    cin>>a[0];
    for(int i=1;i<N;i++)
    {
        cin>>a[i];
        a[i]+=a[i-1];//求前缀和数组
    }
    int ans=0;
    int mubiao=M;//目标
    for(;int index = lower_bound(a, a + N, mubiao)-a;)
    {
        if(index==N)//找不到了说明没有了
        {
            break;
        }
        if(a[index]==M)
        {
            mubiao=a[index]+1;
        }
        else{
            int fl=a[index]-M;
            int ind=lower_bound(a, a + N, fl)-a;
            if(a[ind]==fl)
                ans++;
            mubiao=a[index]+1;//目标加一,防止重复查找
        }
    }
    cout<<ans;
    
    return 0;
}

The idea is to find a number larger than M. If you can find it, then find the difference between this number and M, and then find the difference. If you can find it, then according to the definition of the prefix sum, the sum of this string is equal to M, and then put +1 on target, prevents duplicate lookups.

Six.list(linked list)

Common operation functions:

List.assign() assigns a value to the list 


List.back() returns the last element 


List.begin() returns an iterator pointing to the first element 


List.clear() removes all elements 


List.empty() returns true if the list is empty 


List.end() returns an iterator over the end 


List.erase() deletes an element 


List.front() returns the first element 


List.get_allocator() returns the allocator of the list 


List.insert() inserts an element into the list 


List.max_size() returns the maximum number of elements that the list can hold 


List.merge() merges two lists 


List.pop_back() removes the last element 


List.pop_front() removes the first element 


List.push_back() Add an element at the end of the list 


List.push_front() adds an element to the head of the list 


List.rbegin() returns a reverse iterator pointing to the first element 


List.remove() removes elements from the list 


List.remove_if() Remove elements according to specified conditions 


List.rend() A reverse iterator pointing to the end of the list 


List.resize() changes the size of the list 


List.reverse() reverses the elements of the list 


List.size() returns the number of elements in the list 


List.sort() sorts the list 


List.splice() merges two lists 


List.swap() Exchange the contents of two lists


List.unique() deletes adjacent duplicate elements in the list


definition of list

list<int> lst1;          //创建一个空list

list<int> lst2(10);       //创建一个含有10个元素的list

list<int> lst3(3,2);  //创建含有3个元素2的list

list<int> lst4(lst2);    //使用lst2初始化lst4

list<int> lst5(lst2.begin(),lst2.end());  //同lst4

Part of the content is similar to that of the stack, so we won't talk about it.

 

ヽ( ̄ω ̄( ̄ω ̄〃)ゝ That’s it for today, see you soon!

 

 

 

 

 

Guess you like

Origin blog.csdn.net/apple_59169997/article/details/124127202