stl算法-search

本文介绍了一个使用C++实现的搜索算法案例,展示了如何在不同容器(如双端队列和链表)中查找子序列,并通过自定义谓词进行复杂匹配。通过具体的代码示例,演示了标准模板库(STL)中搜索函数的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//afxstuff.hpp

#ifndef ALGOSTUFF_HPP
#define ALGOSTUFF_HPP

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <functional>
#include <numeric>

using namespace std;

template<class T>
void PRINT_ELEMENTS(const T& collection, const char* optcstr="")
{
	typename T::const_iterator pos;
	std::cout<< optcstr;
	for(pos = collection.begin(); pos != collection.end();++pos)
	{
		std::cout<<*pos<< ' ';
	}

	std::cout<<std::endl;
}

template<class T>
void INSERT_ELEMENTS(T& col, int first, int last)
{
	for (int i = first; i <= last; ++i){
		col.insert(col.end(), i);
	}
}
#endif

//search1.hpp

#ifndef SEARCH1_HPP
#define SEARCH1_HPP

#include "afxstuff.hpp"

void search_test1()
{
	deque<int> dqi;
	list<int> li;
	INSERT_ELEMENTS(dqi, 1, 7);
	INSERT_ELEMENTS(dqi, 1, 7);
	INSERT_ELEMENTS(li, 3, 6);

	PRINT_ELEMENTS(dqi, "deque:");
	PRINT_ELEMENTS(li,"list:");

	deque<int>::iterator dii_pos;
	dii_pos =  search(dqi.begin(), dqi.end(), li.begin(), li.end());
	while (dii_pos != dqi.end())
	{
		cout<< " sub coll found starting with element " << distance(dqi.begin(), dii_pos) +1 << endl;
		++dii_pos;
		dii_pos = search(dii_pos, dqi.end(), li.begin(), li.end());
	}
}


#endif
测试结果:

deque:1 2 3 4 5 6 7 1 2 3 4 5 6 7
list:3 4 5 6
 sub coll found starting with element 3
 sub coll found starting with element 10
请按任意键继续. . .


//search2.hpp

#ifndef SEARCH2_HPP
#define SEARCH2_HPP

#include "afxstuff.hpp"

bool CheckEven(int n, bool is_even){
	if (is_even){
		return n%2==0;
	}
	else {
		return n%2 == 1;
	}
}

void search_test2()
{
	deque<int> dqi;
	list<int> li;
	INSERT_ELEMENTS(dqi, 1, 9);
	PRINT_ELEMENTS(dqi, "deque:");
	bool check_even_params[] = {true, false, true};
	deque<int>::iterator dii_pos;
	dii_pos =  search(dqi.begin(), dqi.end(), check_even_params, check_even_params+3, CheckEven );
	while (dii_pos != dqi.end())
	{
		cout<< " sub coll found starting with element " << distance(dqi.begin(), dii_pos) +1 << endl;
		++dii_pos;
		dii_pos =  search(++dii_pos, dqi.end(), check_even_params, check_even_params+3, CheckEven );
	}
}


#endif

测试结果:

deque:1 2 3 4 5 6 7 8 9
 sub coll found starting with element 2
 sub coll found starting with element 4
 sub coll found starting with element 6
请按任意键继续. . .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值