算法之旅,直奔<algorithm>之四 binary_search

35 篇文章 1 订阅
29 篇文章 0 订阅

binary_search(vs2010)

  • 引言
binary_search是我学习总结<algorithm>的第四篇,这是查找非常厉害的算法,也是非常基础的。不过依赖使用对象容器元素是排序的。
  • 作用
binary_search 作用是在容器中检测容器中是否存在给定值的元素,如果存在则返回true,否则返回 false。
在使用的时候有两个重载,分别如下

  1. template <class ForwardIterator, class T>
      bool binary_search (ForwardIterator first, ForwardIterator last,
                          const T& val);
     
  2. template <class ForwardIterator, class T, class Compare>
      bool binary_search (ForwardIterator first, ForwardIterator last,
                          const T& val, Compare comp);

The elements are compared using operator< for the first version, and comp for the second.
 
  
  • 实验
对数据集合 {1,2,3,4,5,4,3,2,1}进行排序,排序规则有以上两种,可以选择默认(即第一种),也可以自己定义comp。排序后,折半检测容器中是否存在自定义指定元素。
        
  • 代码
test.pp
#include <iostream>     // std::cout
#include <algorithm>    // std::binary_search, std::sort
#include <vector>       // std::vector
#include <array>

bool Condition (int i,int j) 
{ 
	return ( i > j ); 
}

int main () 
{
	std::array<int,10> myints = {1,2,3,4,5,4,3,2,1};
	std::vector<int> v(myints.begin(),myints.end());                         // 1 2 3 4 5 4 3 2 1

	// using default comparison:
	std::sort (v.begin(), v.end());

	std::cout << "looking for a 5... ";
	if (std::binary_search (v.begin(), v.end(), 5))
		std::cout << "found!\n"; 
	else std::cout << "not found.\n";

	// using Condition as comp:
	std::sort (v.begin(), v.end(), Condition );

	std::cout << "looking for a 4... ";
	if (std::binary_search (v.begin(), v.end(), 4, Condition))
		std::cout << "found!\n"; 
	else std::cout << "not found.\n";
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值