algorithm - STL C++

search()

Declaration

template <class FwdIter1, class FwdIter2>
FwdIter1 search(
	FwdIter1 xFirst1,
	FwdIter1 xLast1,
	FwdIter2 xFirst2,
	FwdIter2 xLast2
);

Description

This function finds the first subsequence of entries in the range starting from "xFirst1" up to the entry before "xLast1" that is equal to the sequence of entries in the range from "xFirst2" up to the entry before "xLast2," and returns an iterator that points to the subsequence that was found. If no subsequence was found, the function returns an iterator that points to "xLast1." The overloaded version takes a comparison function, "xComp," and uses that to compare entries instead of equality.

Header Include

#include <algorithm>

Overloads

template <class FwdIter1, class FwdIter2, class Pred>
FwdIter1 search(
	FwdIter1 xFirst1,
	FwdIter1 xLast1,
	FwdIter2 xFirst2,
	FwdIter2 xLast2,
	Pred xComp
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	// Create two vector instances
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char> qS;
	qS.push_back('a');
	qS.push_back('X');

	vector<char>::iterator qIter;
	// Output the vectors
	cout << "Searched Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	cout << "Sought Vector: ";
	for (qIter = qS.begin(); qIter != qS.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Search the first vector for occurences of the second
	qIter = search(qV.begin(), qV.end(), qS.begin(), qS.end());

	// Output the result
	if (qIter != qV.end()) {
		cout << "An occurence of the sought vector was found at the index ";
		cout << (qIter - qV.begin())  << endl;
	} else {
		cout << "No occurence was found in searched vector" << endl;
	}

	// Keep the window open
	cin.get();
	return 0;
}

Output

search() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.