binary_search(vs2010)
引言 binary_search是我学习总结
的第四篇,这是查找非常厉害的算法,也是非常基础的。
作用
binary_search
的
作用是在容器中检测容器中是否存在给定值的元素,如果存在则返回true,否则返回 false。
在使用的时候有两个重载,分别如下
template
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
template
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。排序后,折半检测容器中是否存在自定义指定元素。
代码< http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPgp0ZXN0LnBwCjxwcmUgY2xhc3M9"brush:java;">#include
// std::cout #include
// std::binary_search, std::sort #include
// std::vector #include
bool Condition (int i,int j) { return ( i > j ); } int main () { std::array
myints = {1,2,3,4,5,4,3,2,1}; std::vector
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
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
template
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。排序后,折半检测容器中是否存在自定义指定元素。