Detailed explanation of STL standard class template algorithm (detailed explanation of non-modified sequence algorithm)

        Let’s not talk too much nonsense in this blog, let’s walk into the world of simple operation algorithms together, use the STL class template to simply use the algorithm, the specific operation is as follows:

        code snippet:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void print(int val)
{
	cout<<val<<" ";
}
int main()
{
	vector<int> ivc1;
	cout<<"请输入容器中元素个数:"<<endl;
	int n;
	int x;
	cin>>n;
	cout<<"请输入容器中的元素:"<<endl; 
	for(int i=0;i<n;i++)
	{
		cin>>x;
		ivc1.push_back(x);
	}
	cout<<endl;
	
	//	using sort 
	sort(ivc1.begin(),ivc1.end());
	cout<<"After sort:"<<endl;
	for_each(ivc1.begin(),ivc1.end(),print);
	cout<<endl<<endl;
	
	//	using adjacent_find()
	vector<int>::iterator it;
	it = adjacent_find(ivc1.begin(),ivc1.end());
	cout<<"After adjacent_find():"<<endl;
	cout<<*it<<" ";
	cout<<*it++<<endl;
	cout<<endl;
	
	//	using count()
	int v = count(ivc1.begin(),ivc1.end(),5);
	cout<<"count(5):"<<endl;
	cout<<v<<endl;
	cout<<endl;
	
	//using equal()
	vector<int> ivc2;
	cout<<"输入要比较的容器中的元素:"<<endl; 
	for(int i=0;i<n;i++)
	{
		cin>>x;
		ivc2.push_back(x);
	}
	sort(ivc2.begin(),ivc2.end());
	if(equal(ivc1.begin(),ivc1.end(),ivc2.begin()))
		cout<<"ivc1 and ivc2 相同"<<endl;
	else
		cout<<"ivc1 and ivc2 不相同"<<endl;
		cout<<endl;
		
	//using find()
	cout<<"After find          :"<<endl;
	if(find(ivc1.begin(),ivc1.end(),7)!=ivc1.end())
		cout<<"found 7"<<endl;
	else
		cout<<"not found 7"<<endl;
		cout<<endl;
		
	//using mismatch()
	pair<vector<int>::iterator,vector<int>::iterator> it1;
	it1 = mismatch(ivc1.begin(),ivc1.end(),ivc2.begin());
	cout<<"After mismatch:"<<endl;
	if(it1.first == ivc1.end())
		cout<<"no mismatch."<<endl;
	else
	{
		cout<<"the first mismatch:"<<endl;
		cout<<*it1.first<<" "<<*it1.second<<endl;		
	}
	cout<<endl;
	
	//using search
	vector<int> ivc3;
	ivc3.push_back(1);		//判断1,3序列是否在ivc1中出现过 
	ivc3.push_back(3);
	cout<<"After search():"<<endl;
	it = search(ivc1.begin(),ivc1.end(),ivc3.begin(),ivc3.end());
		if(it!=ivc1.end())
			cout<<"ivc3元素包含在ivc1中"<<endl;	
		else
			cout<<"ivc3元素不包含在ivc1中"<<endl; 
	return 0;	
} 

The running result is shown in the figure below:

The next article will introduce the STL correction sequence algorithm in detail, in the same way as this blog, good night everyone. 

Guess you like

Origin blog.csdn.net/m0_61886762/article/details/124206618
Recommended