binary_search(vs2010)
- 引言
binary_search是我学习总结<algorithm>的第四篇,这是查找非常厉害的算法,也是非常基础的。不过依赖使用对象容器元素是排序的。
- 作用
binary_search
的
作用是在容器中检测容器中是否存在给定值的元素,如果存在则返回true,否则返回 false。
在使用的时候有两个重载,分别如下
-
template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
-
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;
}
-
template <class ForwardIterator, class T> bool binary_search (ForwardIterator first, ForwardIterator last, const T& val);
-
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.
#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;
}