C++ STL常用查找算法小结

前言:

一共讲了6中常用的查找算法.但是查找算法远远不拘泥于此.在调用每一个函数的前面都介绍了查找目的,示例代码虽然简单,学会运用以后会大有作用.

#include
using namespace std;
#include"vector"
#include"map"
#include"string"
#include"list"
#include"set"
#include"functional"
#include"iterator"//输出流迭代器
void main11_adjacent_find()
{
	vector v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(5);
	vector::iterator it = adjacent_find(v1.begin(), v1.end());
	if (it == v1.end())
	{
		cout << "没有找到 重复的元素" << endl;
	}
	else
	{
		cout << *it << endl;
	}
	int index = distance(v1.begin(), it);
	cout << index << endl;
}
void main22_binary_search()//二分法查找,不断的对半分,速度快   返回一个布尔类型
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	v1.push_back(7);
	v1.push_back(9);
	bool b=binary_search(v1.begin(), v1.end(), 7);
	if (b == true)
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}
}
void main33_count()//查找7的个数
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(9);
	int num = count(v1.begin(), v1.end(), 7);
	cout << num << endl;
	
}
bool GreatThree(int iNum)
{
if (iNum > 3)
{
	return true;
}
return false;
  }
void main44_countif()//查找元素大于3的个数
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(9);
	int num = count_if(v1.begin(), v1.end(), GreatThree);
	cout <<"num"<< num << endl;

}
void main55_find()//查找第一个5的位置
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(9);
	vector::iterator it = find(v1.begin(), v1.end(),5);
	cout << "*it" << *it << endl;
}
void main66_findif()//查找大与3的位置  可以查找自定义的
{
	vector v1;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(7);
	v1.push_back(9);
	vector::iterator it = find_if(v1.begin(), v1.end(), GreatThree);
	cout << "*it" << *it << endl;
}
void main()
{
	main11_adjacent_find();
	main22_binary_search();
	main33_count();
	main44_countif();
	main55_find();
	main66_findif();
	cout << "hello..." << endl;
	system("pause");
	return;
}

@@

展开阅读全文

页面更新:2024-04-29

标签:算法   常用   目的   布尔   示例   小结   前言   函数   个数   元素   作用   位置   类型   代码   简单   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top