C++笔记 二分搜索算法

primer C++笔记

二分搜索算法

在这里插入图片描述

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

//二分搜索算法

//lower_bound(beg, end, val);
//lower_bound(beg, end, val, comp);
//upper_bound(beg, end, val);
//upper_bound(beg, end, val, comp);
template<class ForwardIt, class T, class Compare = std::less<>>
ForwardIt binary_find(ForwardIt first, ForwardIt last, const T& value, Compare comp = {})
{
	// 注意:类型 T 和 Forward 解引用后的类型都必须可隐式转换为
	// 用于 Compare 的 Type1 和 Type2 。
	// 这严格于 lower_bound 要求(见上述)

	first = std::lower_bound(first, last, value, comp);
	return first != last && !comp(value, *first) ? first : last;
}
void test01()
{
	std::vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 };

	auto lower = std::lower_bound(data.begin(), data.end(), 4);
	auto upper = std::upper_bound(data.begin(), data.end(), 4);

	std::copy(lower, upper, std::ostream_iterator<int>(std::cout, " "));

	std::cout << '\n';

	// 经典二分搜索,仅若存在才返回值

	data = { 1, 2, 4, 6, 9, 10 };

	auto it = binary_find(data.cbegin(), data.cend(), 4); // 选择 '5' 的 < 将返回 end()

	if (it != data.cend())
		std::cout << *it << " found at index " << std::distance(data.cbegin(), it);

	//4 4 4
	//4 found at index 2
}

//equal_range(beg, end, val);
//equal_range(beg, end, val, comp);
struct S
{
	int number;
	char name;
	// 注意:此比较运算符忽略 name
	bool operator< (const S& s) const { return number < s.number; }
};
void test02()
{
	// 注意:非有序,仅相对于定义于下的 S 划分
	std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4,'G'}, {3,'F'} };

	S value = { 2, '?' };

	auto p = std::equal_range(vec.begin(), vec.end(), value);

	for (auto i = p.first; i != p.second; ++i)
		std::cout << i->name << ' ';


	// 异相比较:
	struct Comp
	{
		bool operator() (const S& s, int i) const { return s.number < i; }
		bool operator() (int i, const S& s) const { return i < s.number; }
	};

	auto p2 = std::equal_range(vec.begin(), vec.end(), 2, Comp{});

	for (auto i = p2.first; i != p2.second; ++i)
		std::cout << i->name << ' ';

	//B C D B C D
}

//binary_search(beg, end, val);
//binary_search(beg, end, val, comp);
void test03()
{
	std::vector<int> haystack{ 1, 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";
		}
	}

	/*Searching for 1
	Found 1
	Searching for 2
	no dice!
	Searching for 3
	Found 3*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值