STL標準テンプレートアルゴリズムの詳細説明(非改変シーケンスアルゴリズムの詳細説明)

        このブログではあまりくだらない話はやめて、一緒に単純な演算アルゴリズムの世界を歩きましょう。アルゴリズムを単純に使用するには STL クラス テンプレートを使用します。具体的な演算は次のとおりです。

        コードスニペット:

#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;	
} 

実行結果を次の図に示します。

次回はこのブログと同様にSTL補正シーケンスのアルゴリズムを詳しく紹介していきます、皆さんおやすみなさい。 

おすすめ

転載: blog.csdn.net/m0_61886762/article/details/124206618