algorithm - STL C++

search_n()

Declaration

template <class FwdIter, class Size, class X>
FwdIter search_n(
	FwdIter xFirst,
	FwdIter xLast,
	Size xCount,
	const X& kxrValue
);

Description

This function finds the first subsequence of entries in the range starting from "xFirst" up to the entry before "xLast" that is equal to the sequence of "xCount" consecutive entries that are equal to "kxrValue" 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 "xLast." The overloaded version takes a comparison function, "xComp," and uses that to compare entries instead of equality.

Header Include

#include <algorithm>

Overloads

template <class FwdIter, class Size, class X, class Pred>
FwdIter search_n(
	FwdIter xFirst,
	FwdIter xLast,
	Size xCount,
	const X& kxrValue,
	Pred xComp
);

Example

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

int main()
{
	using namespace std;

	// Create a vector instance
	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>::iterator qIter;
	// Output the vectors
	cout << "Searched Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	for (int i = 0; i < 3; ++i) {
		// Search the vector for consecutive occurences of 'a'
		qIter = search_n(qV.begin(), qV.end(), i, 'a');

		// Output the result of the search
		if (qIter != qV.end()) {
			cout << "Found " << i << " consecutive \'a\'s at the index ";
			cout << (qIter - qV.begin())  << endl;
		} else {
			cout << "Did not find " << i << " consecutive \'a\'s" << endl;
		}
	}

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

Output

search_n() Output
 

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