STL-アルゴリズム:検索

コードで話す:

# include<iostream>
# include<algorithm>
# include<vector>

using namespace std;

class Person{
	public:
		Person(int a,int b):id(a),age(b){} 
		bool operator==(Person p2){
			return this->age == p2.age && this->id == p2.id;
		}
	public:
		int id;
		int age;
};

void test1()
{//find(beg,end,elem)
	cout << "查找基本数据类型:" << endl;
	
	vector<int> v1;
	v1.push_back(2);
	v1.push_back(5);
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(4);
	vector<int>::iterator ret = find(v1.begin(),v1.end(),5);
	if(ret != v1.end())
		cout << "找到:" << *ret << endl;
	else
		cout << "未找到!" << endl;
		
	cout << "--------" << endl;
	cout << "查找自定义数据类型:" << endl;
	vector<Person> v2;
	Person p1(1,4),p2(2,5),p3(3,6),p4(2,4);
	v2.push_back(p1);
	v2.push_back(p2);
	v2.push_back(p3);
	
	vector<Person>::iterator itP4 = find(v2.begin(),v2.end(),p4);
	if(itP4 != v2.end())
		cout << "在容器中找到p4(2,4)" << endl;
	else
		cout << "在容器中未找到p4(2,4)k!" << endl;
	
	vector<Person>::iterator itP1 = find(v2.begin(),v2.end(),p1);
	if(itP1 != v2.end())
		cout << "在容器中找到p1(1,4)" << endl;
	else
		cout << "在容器中未找到p1(1,4)!" << endl;
}

void test2()
{//binary_search二分查找
	cout << "查找基本数据类型:" << endl;
	vector<int> v1;
	v1.push_back(2);
	v1.push_back(5);
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(4);
	sort(v1.begin(),v1.begin()+5);
	bool ret5 = binary_search(v1.begin(),v1.end(),5);
	if(ret5)
		cout << "查找到5" << endl;
	else
		cout << "未找到5" << endl;                                                                                                             
}

void test3()
{//adjacent_find(beg,end)查找相邻重复元素 
	vector<int> v1;
	v1.push_back(2);
	v1.push_back(2);
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(4);
	
	vector<int>::iterator it = adjacent_find(v1.begin(),v1.end());
	if(it == v1.end())
		cout << "没有重复相邻的元素!" << endl;
	else
		cout << "有重复相邻的元素:" << *it << endl; 
}

bool MySearch(int val)
{
	return val > 3;
}

void test4()
{//find_if(beg,end,callback)条件查找,callback为回调函数
	vector<int> v1;
	v1.push_back(2);
	v1.push_back(5);
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(4);
	
	vector<int>::iterator it = find_if(v1.begin(),v1.end(),MySearch);
	if(it != v1.end())
		cout << "找到第一个大于3的元素:" << *it << endl;
	else
		cout << "查找失败!" << endl;
}

bool condition(int val)
{
	return val > 2;
}

void test5()
{//count(beg,end,value) count_if(beg,end,callback)
	vector<int> v1;
	v1.push_back(2);
	v1.push_back(5);
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(4);
	
	int num1 = count(v1.begin(),v1.end(),1);
	cout << "等于1的元素数量:" << num1 << endl;
	int numl2 = count_if(v1.begin(),v1.end(),condition);
	cout << "大于2的元素数量:" << numl2 << endl;
 } 

int main()
{
	//test1();//find(beg,end,elem)
	//test2();//binary_search(beg,end,value)
	//test3();//adjacent_find(beg,end)查找相邻重复元素 
	//test4();//find_if(beg,end,callback)条件查找,callback为回调函数
	test5();//count(beg,end,value)
	
 return 0;
}

演算結果:

test1:

test2:

test3:

test4:

test5: 

おすすめ

転載: blog.csdn.net/qq_40479037/article/details/87293079