algorithm - STL C++

adjacent_find()

Declaration

template <class ForwardIterator>
ForwardIterator adjacent_find(
	ForwardIterator qFirst,
	ForwardIterator qLast
);

Description

This function searches the entries from "qFirst" to the one before "qLast" for two adjacent entries that are equal. If a pair of equal adjacent entries are found, an iterator that points to the first one is returned. Otherwise, the "qLast" iterator is returned to indicate that no pair of equal adjacent entries was found. In the overloaded version, the function takes a third argument called "qComp". The BinaryPredicate "qComp" is a comparison function, like equals, that can return true. When the argument "qComp" is used, the function searches for two adjacent entries that satisfy "qComp".

Header Include

#include <algorithm>

Overloads

template <class ForwardIterator,class BinaryPredicate>
ForwardIterator adjacent_find(
	ForwardIterator qFirst,
	ForwardIterator qLast
	BinaryPredicate qComp
);

Example

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

// Comparison function
bool OneMoreThan(int iInt1, int iInt2) {
	return ((iInt1 + 1) == iInt2);
}

int main()
{
	using namespace std;

	vector<int> qV;
	// Put entries into the vector [4, 2, 3, 3, 5]
	qV.push_back(4);
	qV.push_back(2);
	qV.push_back(3);
	qV.push_back(3);
	qV.push_back(5);

	// Check for equal adjacent entries
	vector<int>::iterator qFound = adjacent_find(qV.begin(), qV.end());
	cout << "First Search:" << endl;
	if (qFound == qV.end()) {
		cout << "Not Found" << endl;
	} else {
		cout << "Found with value = " << (*qFound) << endl;
	}

	// Check for OneMoreThan() adjacent entries
	qFound = adjacent_find(qV.begin(), qV.end(), OneMoreThan);
	cout << "Second Search with Comparison:" << endl;
	if (qFound == qV.end()) {
		cout << "Not Found" << endl;
	} else {
		cout << "Found with value = " << (*qFound) << endl;
	}
	cin.get();
	return 0;
}

Output

adjacent_find() Output
 

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