(12)C++算法---查找,排序,std::sort,std::find,std:search,std::binary_search


#include <iostream>
#include <thread>
#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
using namespace std;

struct Point  //对类也是一样的
{
	Point(int _x,int _y) {
		x = _x;
		y = _y;
	}
	int x;
	int y;

};

static bool compare_by_x(const Point &p1,const Point &p2)  //自定义比较函数
{
	if (p1.x < p2.x) 
	{
		return true;
	}
	return false;
}

static bool binary_search_by_x(const Point &p1,const Point &p2)
{
	if (p1.x < p2.x)//这里为什么是小于号?如果有序容器是从小到大排列则用小于号,如果有序容器从大到小排则用大于号
		//二分查找的规则是负责从中间开始查找,定位需要查找的那个数的位置,再对位置上的数字与查找的数字做比较。
		//前期找位置的过程中只需要告诉算法你这个数是大了还是小了
	{
		return true;
	}
	return false;
}

int main()
{
	//排序
	vector<int> vec = { 1,3,5,4,2,6,5,9,8,3,5 };
	vector<int> vec1 = { 10,20,30,40,50,60,70,80 }; 

	vector<Point> vec_point;
	vec_point.push_back(Point(1, 2));
	vec_point.push_back(Point(3, 2));
	vec_point.push_back(Point(2, 2));
	vec_point.push_back(Point(4, 2));

	std::sort(vec.begin(), vec.end()); //对容器的简单排序,默认排序规则从小到大
	//自定义排序规则
	std::sort(vec_point.begin(), vec_point.end(),compare_by_x);

	//查找
	string s1 = " hello world";
	string s2 = "llo";
	
	auto it = std::find(s1.begin(), s1.end(), 'o');//查找迭代器中单个对象用find
	int dis = static_cast<int>(std::distance(s1.begin(), it));

	auto it1 = std::search(s1.begin(), s1.end(), s2.begin(), s2.end());//查找迭代器中对象区间用seach
	int dis1 = static_cast<int>(std::distance(s1.begin(), it1));
	if(it1!=s1.end())
	{
		cout << "found in:" << dis1 << endl;
	}
	else
	{
		cout << "not found" << endl;
	}

	std::vector<int> haystack{ 1,/*6,*/ 3, 4, 5, 9 }; //二分查找带查找容器必须有序,否则查找结果错误
	std::vector<int> needles{ 1, 2, 3 };

	for (auto needle : needles)
	{
		std::cout << "Searching for " << needle << '\n';
		if (std::binary_search(haystack.begin(), haystack.end(), needle))//二分查找,找到返回真,否则返回假
		{
			std::cout << "Found " << needle << '\n';
		}
		else {
			std::cout << "no dice!\n";
		}
	}

	//二分查找自定义查找规则,二分查找的入口容器必须是有序容器,否则查找错误
	bool found = std::binary_search(vec_point.begin(), vec_point.end(), Point(4, 4), binary_search_by_x);

	system("pause");

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章