C++ STL非更易型算法 查找第一个子区间search使用方法

在这里插入图片描述

返回[_First,_Last)区间内与[_First2,_Last2)区间完全吻合的第一个子区间内的第一元素位置,子区间内的元素必须完全等于[_First2,_Last2)的元素

在这里插入图片描述

返回[_First,_Last)区间内与[_First2,_Last2)区间完全吻合的第一个子区间内的第一元素位置,子区间内的元素必须造成_Pred(elem,searchElem)结果为true.

如果没有找到匹配元素,返回end

复杂度:线性

template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
	for (int i = first; i <= last; ++i)
	{
		coll.insert(coll.end(), i);
	}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
	cout << optcstr;
	for (auto elem : coll)
	{
		cout << elem << ' ';
	}
	cout << endl;

}
int main()
{
	deque<int>coll;
	list<int>subcoll;
	INSERT_ELEMENTS(coll, 1, 7);
	INSERT_ELEMENTS(coll, 1, 7);
	INSERT_ELEMENTS(subcoll, 3, 6);
	PRINT_ELEMENTS(coll, "coll: ");
	PRINT_ELEMENTS(subcoll, "subcoll: ");
	auto pos = search(coll.begin(), coll.end(), subcoll.begin(), subcoll.end());
	while (pos != coll.end())
	{
		cout << "subcoll found starting with element " << distance(coll.begin(), pos) + 1 << endl;
		++pos;
		pos = search(pos, coll.end(), subcoll.begin(), subcoll.end());
	}
}

在这里插入图片描述

下面的例子使用search查找偶数、奇数、偶数排列而成的子序列:

int main()
{
	vector<int>coll;
	INSERT_ELEMENTS(coll, 1, 9);
	PRINT_ELEMENTS(coll, "coll: ");
	bool checkEvenArgs[3] = { true, false, true };
	auto pos = search(coll.begin(), coll.end(), checkEvenArgs, checkEvenArgs + 3, checkEven);

	while (pos != coll.end())
	{
		cout << "subrange found starting with element " << distance(coll.begin(), pos) + 1 << endl;
		pos = search(++pos, coll.end(), checkEvenArgs, checkEvenArgs + 3, checkEven);
	}

	
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值