C++STL之查找子序列的算法

时间:2021-12-27 05:50:48
//----------------------------------------------------------------------------------------  
//      Desc:       STL search() used in vector container and struct data  
//      Author:     spring brother  
//      Data:       2018.3.24  
//      Copyright (C) 2018 spring brother  
//----------------------------------------------------------------------------------------  

/*
查找子序列的算法
search(beg1,end1,beg2,end2)
search(beg1,end1,beg2,end2,binaryPred)
返回第二个输入范围(子序列)在第一个输入范围中第一次出现的位置。如果未找到子序列,则返回end1。

find_first_of(beg1,end1,beg2,end2)
find_first_of(beg1,end1,beg2,end2,binaryPred)
返回一个迭代器,指向第二个输入范围中任意元素在第一个范围中首次出现的位置。如果未找到匹配元素,则返回end1。

find_end(beg1,end1,beg2,end2)
find_end(beg1,end1,beg2,end2,binaryPred)
类似search,但是返回的是最后一次出现的位置。如果第二个输入范围为空,或者在第一个输入范围中未找到它,则返回end1。
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

bool isEqual(int &i, int &j) {
return i == j / 2;
}

int main()
{
int arrIn[6] = { 1,2,4,4,4,5 };
int arrSub[3] = { 2,4,4 };
vector<int> vecIn(arrIn, arrIn + 6);
vector<int> vecSub(arrSub, arrSub + 3);

vector<int>::iterator it = search(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end()); //search
if (it != vecIn.end()) {
cout << "search = " << *it << endl;
}
it = search(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end()-1,isEqual); //search,传入仿函数
if (it != vecIn.end()) {
cout << "search = " << *it << endl;
}
it = search(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end()-1, [](int &i, int &j) {return i == j / 2; }); //search,传入仿函数
if (it != vecIn.end()) {
cout << "search = " << *it << endl;
}

int arrSub_1[3] = { 7,8,5 };
vector<int> vecSub_1(arrSub_1, arrSub_1 + 3);
it = find_first_of(vecIn.begin(), vecIn.end(), vecSub_1.begin(), vecSub_1.end()); //find_first_of
if (it != vecIn.end()) {
cout << "find_first_of = " << *it << endl;
}
it = find_first_of(vecIn.begin(), vecIn.end(), vecSub_1.begin(), vecSub_1.end() - 1, isEqual); //find_first_of,传入仿函数
if (it != vecIn.end()) {
cout << "find_first_of = " << *it << endl;
}
it = find_first_of(vecIn.begin(), vecIn.end(), vecSub_1.begin(), vecSub_1.end() - 1, [](int &i, int &j) {return i == j / 7; }); //find_first_of,传入仿函数
if (it != vecIn.end()) {
cout << "find_first_of = " << *it << endl;
}

it = find_end(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end()); //find_end
if (it != vecIn.end()) {
cout << "find_end = " << *it << endl;
}
it = find_end(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end() - 1, isEqual); //find_end,传入仿函数
if (it != vecIn.end()) {
cout << "find_end = " << *it << endl;
}
it = find_end(vecIn.begin(), vecIn.end(), vecSub.begin(), vecSub.end() - 1, [](int &i, int &j) {return i == j / 2; }); //find_end,传入仿函数
if (it != vecIn.end()) {
cout << "find_end = " << *it << endl;
}

    return 0;
}