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

 

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