继续学习STL算法,本文主要讲几种基本的搜索和排序算法:
- find:查找,返回一个输入迭代器,指向第一个含有搜索值的元素或序列的末端(没找到的话)
- find_if:查找满足一定条件的,需要一个函数作为参数。
- sort:排序。
- binary_search:搜索,在搜索之前,这个序列必须要先以递增的顺序排序,返回bool值,表明是否搜索到了目标。
源代码如下:
// Fig22_29_STL_Alg_find_sort_binary_search.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>//ostream_iterator
using namespace std;
bool greater10(int value);//prototype
int main()
{
// std::cout << "Hello World!\n";
const int SIZE = 10;
int a[SIZE] = { 10,2,17,5,16,8,13,11,20,7 };
vector<int> v(a, a+ SIZE);//copy of a
ostream_iterator<int> output(cout, " ");
cout << "Vector v contains: \n";
copy(v.begin(), v.end(), output);//display output vector
//locate first occurrence of 16 in v
vector<int>::iterator location;
location = find(v.begin(),v.end(),16);
if (location != v.end())//found 16
{
cout << "\n\nFound 16 at location:" << (location - v.begin());
cout << "\n\n*location is what?*location is:" << *location;
cout << "\n\n&location is what?&location is:" << &location;
}
else
{
cout << "\n\n16 not found";
}
//locate first occurrence of 100 in v
location = find(v.begin(),v.end(),100);
if (location != v.end())//found 100
{
cout << "\n\nFound 100 at location:" << (location - v.begin());
}
else//100 not found
{
cout << "\n\n100 not found";
}
//locate first occurrence of value greater than 10 in v
location = find_if(v.begin(), v.end(), greater10);
if (location != v.end())//found
{
cout << "\n\nThe first value greater than 10 is:" << *location<<"\nfound at location:"<<(location - v.begin());
}
else// not found
{
cout << "\n\nNo value is greater than 10";
}
//sort elements of v sort is important very important!
sort(v.begin(), v.end());
cout << "\n\nVector v after sort: ";
copy(v.begin(), v.end(), output);//display output vector
//use binary_search to locate 13 in v
if (binary_search(v.begin(),v.end(),13))
cout << "\n\n13 was found in v";
else
cout << "13 was not found in v";
//use binary_search to locate 100 in v
if (binary_search(v.begin(), v.end(), 100))
cout << "\n\n100 was found in v";
else
cout << "\n\n100 was not found in v";
}
bool greater10(int x)
{
return x > 10;
}
运行结果:
Vector v contains:
10 2 17 5 16 8 13 11 20 7
Found 16 at location:4
*location is what?*location is:16
&location is what?&location is:0036FC0C
100 not found
The first value greater than 10 is:17
found at location:2
Vector v after sort: 2 5 7 8 10 11 13 16 17 20
13 was found in v
100 was not found in v