转接自STL算法
1. find() 查找与被传入值相等的第一个元素
2. find_if() 查找满足谓词的第一个元素
3. find_if_not() 查找第一个不满足谓词的元素(start from c++11)
4. search_n() 查找具备某特性的前n个元素
5. search() 查找某个子区间第一次的出现位置
6. find_end() 查找某个子区间最后出现的位置
7. adjacent_find() 查找连续两个符合特定准则的元素
8. find_first_of() 查找第一个满足谓词中对于子区间可能值的元素
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
// 1. find() 查找与被传入值相等的第一个元素
// 2. find_if() 查找满足谓词的第一个元素
// 3. find_if_not() 查找第一个不满足谓词的元素(start from c++11)
// 4. search_n() 查找具备某特性的前n个元素
// 5. search() 查找某个子区间第一次的出现位置
// 6. find_end() 查找某个子区间最后出现的位置
// 7. adjacent_find() 查找连续两个符合特定准则的元素
// 8. find_first_of() 查找第一个满足谓词中对于子区间可能值的元素
void test(const vector<int>& vec)
{
//1
auto fpos = find(vec.begin(), vec.end(), 5);
if (fpos != vec.end())
cout << "had founded " << *fpos << endl;
//2
auto f = [](const int& value)
{
return value % 2 == 0;
};
//查找第一个值为偶数的元素
auto dpos = find_if(vec.begin(), vec.end(), f);
if (dpos != vec.end())
cout << "the first double-value is " << *dpos << endl;
//3
//查找第一个值不为偶数(即奇数)的元素
auto spos = find_if_not(vec.begin(), vec.end(), f);
if (spos != vec.end())
cout << "the first sigle-value is " << *spos << endl;
//4
//查找前连续4个小于5的元素(谓词默认使用equal_to<>())
auto lpos = search_n(vec.begin(), vec.end(), 4, 5,less<int>());
if (lpos != vec.end())
{
cout << "the first serial four value less than five is ";
for (auto it = lpos; it < lpos + 4; ++it)
cout << *it << ends;
}
cout << endl;
//5
vector<int> subvec{ 4,5,6 };
auto subpos = search(vec.begin(), vec.end(), subvec.begin(), subvec.end());
if (subpos != vec.begin())
{
cout << "the subvec is ";
for (auto it = subpos; it < subpos + subvec.size(); ++it)
cout << *it << ends;
}
cout << endl;
//6
vector<int> loop{ 4,5,6,4,4,5,4,5,6 };
auto lastpos = find_end(loop.begin(), loop.end(), subvec.begin(), subvec.end());
if (lastpos != loop.end())
{
cout << "the last subvec is ";
for (auto it = lastpos; it < lastpos + subvec.size(); ++it)
cout << *it << ends;
}
cout << endl;
//7
auto two_minus = [](const int& a, const int& b)
{
return b - a == 4;
};
//默认谓词为equal_to<>()
auto adjacent_pos = adjacent_find(vec.begin(), vec.end(),two_minus);
if (adjacent_pos != vec.end())
{
cout << *(adjacent_pos + 1) << " - " << *adjacent_pos << "= 4" << endl;
}
//8
//查找第一个大于subvec里可能值的元素(Pred默认是equal_to<>())
auto first_pos = find_first_of(vec.begin(), vec.end(), subvec.begin(), subvec.end(),greater<int>());
if (first_pos != vec.end())
cout << "the first value greater than someone of subvec " << *first_pos << endl;
}
int main()
{
vector<int> vec{ 1,2,3,3,4,5,6,3,7,8,3 };
test(vec);
system("pause");
return 0;
}