STL commonly used containers and commonly used functions

Written on the front: This is April again. In the past, at this time of the year, the Blue Bridge provincial competition ended early. This year, affected by the new crown virus, the college entrance examination Blue Bridge Level 4 and 6 have been postponed. It must be unprecedented. I hope there is no one to come! Due to the postponement of Blue Bridge this year, we still haven't started school yet, and the preparation time is extremely long. I have been playing these days, so please calm down and come to a blog. STL can greatly reduce the amount of our code in our daily code problem data structure problem. It can solve your sorting, de-duplication, and full arrangement with a single function.

Topic: Using STL Containers and Functions in C++ Skillfully in the Blue Bridge Cup Competition

I think there are several commonly used STL containers: queue, set, vector, string

There are several commonly used STL algorithms: sort, next_permutation and prev_permutation functions

table of Contents

Topic: Using STL Containers and Functions in C++ Skillfully in the Blue Bridge Cup Competition

One, queue container

Two, set container

Three, vector container

Four, string container

Five, sort function

Default dictionary ascending order

Use cmp to customize the sort type:

Six, next_permutation and prev_permutation functions

 


One, queue container

Queue——The elements inside are subject to first-in-first-out. Generally speaking, you put 123456 in in order. When you take out, the order is still 123456. This is widely used when writing Guangsou (because you First traverse to the point and then traverse to be prioritized). You can think of him as a bucket. You throw something in it today. The first thing you get when you get it is the one you throw in first.

Common methods of operation:

You must first quote the header file: #include <queue>

Define a queue (in the angle brackets are the types of elements in the queue, there can be many types, structures can also be used and are commonly used): queue<int >q;

Insert an element: q.push(a);

Return to the head element: q.front();

Pop the leader element:  q.pop();

Query queue length:  q.size();

Query whether the queue is empty (return value is true or false of type bool): q.empty(); 

Query the tail element: q.back();

note:

(1) It must be C++, and use namespace std;

(2) The header file must be quoted: #include <queue>

(3) After taking the first element of the team, the first element of the team must pop up, otherwise you will always get him. The fetch is just the value, and it is not taken out of the bucket, and the elements behind it have a chance to come out.

Examples:

#include <stdio.h>
#include <queue>
using namespace std; 
int main()
{
	queue<int >q;                       //定义存储类型为int的队列 
	int x;
	printf("输入五个整数:");
	for(int i = 1;i<=5;i++)
	{
		scanf("%d",&x);
		q.push(x);				        //每个x都入队 
	}
	printf("全部出队为:\n");
	while(!q.empty())			        //当q不为空时 
	{
		printf("%d ",q.front());		//输出队首元素 
		q.pop();						//弹出队首元素,队列长度减小
		printf("队列现在的大小:%d\n",q.size()); 
	}
	return 0;
}

Test run:

Two, set container

The set has a feature, the elements in it only appear once, that is, the elements you put in will not be repeated. If you want to put the repeating, it will not put it in for you, then this feature can be used effectively To remove the weight. Moreover, the elements that enter the set are automatically sorted in a dictionary. This set traversal uses iterators, which are pointers to internal elements.

Common methods of operation:

Returns the number of elements of a certain value: count();

If the collection is empty, return true: empty();

Return an iterator to the last element: end();

Return an iterator pointing to the first element: begin();

Delete elements in the collection: erase();

Return an iterator pointing to the element found: find();

Insert elements in the collection: insert();

The number of elements in the collection: size();

Examples:

#include <stdio.h>
#include <set>
using namespace std; 
int main()
{
	set<int >s;                 //定义存储类型为int的set
	int x;

	printf("输入五个整数:");
	for(int i = 1;i<=5;i++)
	{
		scanf("%d",&x);
		s.insert(x);				//每个x放入set容器 
	}
	if (s.find(3)!=s.end())                //查找元素3 
	    printf("Y\n"); 
	else                 
	    printf("N\n"); 
	s.erase(3);						//删除元素3 
	if (s.find(3)!=s.end())   				//再次查找元素3 
	    printf("Y\n"); 		
	else                 
	    printf("N\n"); 
	printf("%d\n",s.size()); 			//容器大小 
	printf("遍历set容器:\n");
	for (set<int>::iterator it = s.begin(); it != s.end(); it++)    //迭代器遍历容器 
	{
	printf("%d",*it); 	
	}
	return 0;
}

 

Test run:

Three, vector container

Similar to array usage, you can directly use subscripts to get values, but you can't use subscripts to assign values! ! ! The characteristic is the use of related functions to calculate the size of the array and whether it is empty

Common operations:

Define v container:

vector<T> v1; //vevtor saves objects of type T. The default construction v1 is empty.
vector<T> v2(v1); //v2 is a copy of v1, the element types of v1 and v2 must be the same
vector<T> v3(n,i); //v3 contains n elements with value i
vector< T> v4(n); //v4 contains n copies of the initialized element, the default element value is 0

Put x into the container: push_back(x);    

Container size: size();

The container is empty: empty();

Examples:

#include <stdio.h>
#include <vector>
using namespace std; 
int main()
{
	vector<int >v;                 //定义存储类型为int的v
	int x;

	printf("输入五个整数:");
	for(int i = 1;i<=5;i++)
	{
		scanf("%d",&x);
		v.push_back(x);				//每个x放入v容器 
	}
	for(int i=0;i<v.size();i++)    //遍历v的大小 
	{
		printf("%d\n",v[i]);
	}
	
	return 0;
}

Test run:

Four, string container

Similar to char array but better to use, you can directly add and subtract or use related functions

Common operations:

Define the s container:
     string s1; //initialize the string, s1 is empty
     string s2 = s1;? //copy initialization, copy s1 to s2
     string s3 = "test"; //direct initialization, s3 is "test"
     string s4 (10,'a'); //s4="aaaaaaaaaa"
     string s6("test"); //Direct initialization
string splicing: direct addition and subtraction: s+="xxxx"; s+=s1;
string search: find ("te");
0-2 position replacement: replace(0, 2, "tt");
compare s1, s2: s1.compare(s2)
take 1-3 position substring: substr(1, 3);
insert Before position 3: insert(3, "tt");
delete characters at position 0-2: erase(0, 2);

Examples:

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std; 
int main()
{
	string s = "0123456";               //定义s 
	string s2 = "789";					//定义s2 
	cout<<s.find("34")<<endl;			//在s查找"34" 
	cout<<s.compare(s2)<<endl;			//比较s和s2 
	s.replace(0, 2, "***");//替换 
	cout<<s<<endl;
	string s3 = s.substr(1, 3);//取子串 
	cout<<s3<<endl;
	s.insert(5, "---");//插入 
	cout<<s<<endl;
	s.erase(0, 4);//删除 
	cout<<s<<endl;
	s+=s2;//叠加 
	cout<<s<<endl;
	return 0;
}

Test run:

 

Five, the sort function in <algorithm>

Default dictionary ascending order

Sort function, default ascending sort, time complexity n*lg(n) , belongs to optimized quick sort

Instructions:

Sort a[0] to a[9] in ascending order: sort(a,a+10);

Examples:

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	int a[110] = {1,3,5,8,7,4,1,2,3,6,9,8,0};
	sort(a,a+10);
	for(int i=0;i<13;i++)
		cout<<a[i]<<" ";
	return 0;
} 

Test run:

Use cmp to customize the sort type:

Simple ascending sorting cannot meet everyone's needs, so you can rewrite the parameter passing function cmp as the three parameters of the word sort to customize the sorting method. There are many ways to write functions, such as structure sorting. You can use a certain element of the structure to sort, etc.

Examples:

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp1(int a,int b)//传参为排序数据类型
{
    return a>b;//降序排列(你需要的排序规则) 
}
int main()
{
	int a[110] = {1,3,5,8,7,4,1,2,3,6,9,8,0};
	sort(a,a+10,cmp1);
	for(int i=0;i<13;i++)
		cout<<a[i]<<" ";
	return 0;
} 

Test Results:

Six, next_permutation and prev_permutation functions in <algorithm>

Two full permutation functions, next is the next permutation, prev is the previous one, and it will perform the lexicographical permutation according to your parameters, so

Note: Before you use this function, you must ensure that the data you pass to it is monotonous (you can sort()), otherwise it will be incomplete! ! ! !

Explanation: For example, if you pass the parameter "231" to next, he will find the next order in lexicographical order, while the "123" sequence is above him, and this sequence will not be traversed! ! !

Instructions:

Use do-while, put the function in the while, put the processing statement in the do, the sorted sequence still exists in the original array, and then proceed to the next dictionary arrangement,,, you must pay attention that you can’t perform array elements in do Assignment and other operations can only take values, because the assignment will affect the next full row! ! ! !

Examples:

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	char a[110] = "123";
	do
	{
		for(int i =0;i<6;i++)
			printf("%c ",a[i]);
		printf("\n");
		
	}
	while(next_permutation(a,a+3));
	return 0;
} 

 

Test run:

 

 

 

In general, using these containers can reduce the amount of our code. There are many usages and a lot of precautions. For the time being, I understand only this point. I can only share this point. I will learn about others later and will come again. Any experience exchange or other welcome comments, or Q me 2905257286

 

 

Guess you like

Origin blog.csdn.net/qq_41170600/article/details/105455961