adjacent_find STL Algorithm

Adjacent_find( ) STL Algorithm

Thea adjacent_find()algorithm searches for adjacent matching elements within a sequence specified by start and end and returns an iterator to the first element. If no adjacent pair is found, end is returned.
The first version looks for equivalent elements. The second version lets you specify your own method for determining matching elements.

Syntax:


template< class ForwardIterator > ForwardIterator adjacent_find( ForwardIterator first, ForwardIterator last );

template< class ForwardIterator, BinaryPredicate my_func > ForwardIterator adjacent_find( ForwardIterator first, ForwardIterator last, BinaryPredicate my_func );

Implementation of Adjacent_find( ) STL Algorithm in C++. Example of main is provided for testing purposes.

#include <list>
#include <algorithm>
#include <iostream>

using namespace std;

typedef int type;

// Returns if from two adjacent matching the first is smaller one.
bool my_less (int item1, int item2 )
{
 return (item1= item1 > item2);
}//end of less

//print using iterators
void print(list <type>::iterator it, list <type> adjacentlist)
{
 cout<< "my sequence is: ";
 for ( it = adjacentlist.begin( ); it != adjacentlist.end( ); it++ )
 cout << *it << " ";
 cout << endl;
}//emnd of print
int main()
{
int const size=8;
list <type> adjacentlist;
list <type>::iterator search1, search2;
list <type>::iterator it;
//load adjacent list
for(int j=0; j< size;j++)
{
adjacentlist.push_back(2*j+1);
if(j== 5) adjacentlist.push_back(2*j+1);
if(j== 5) adjacentlist.push_back(2*j-1);

}
//print adjacent list
print(it,adjacentlist);

//using adjacent_find( )

search1 = adjacent_find( adjacentlist.begin( ), adjacentlist.end( ) );
 if ( search1 == adjacentlist.end( ) )
 cout << "There are not two adjacent elements that are equal."<< endl;
else
 cout << "There are two adjacent elements that are equal, value of: "<< *search1<< endl;
search2 = adjacent_find( adjacentlist.begin( ), adjacentlist.end( ), my_less );
 if ( search2 == adjacentlist.end( ) )
 cout << "There are not two adjacent elements that the first is less that the second."<< endl;
else
 cout << "There are two adjacent elements that the first is less that the second: "<< *search2<< " " << *search2++<< endl;
}//end of main

Program Output:


my sequence is: 1 3 5 7 9 11 11 9 13 15
There are two adjacent elements that are equal, value of: 11
There are two adjacent elements that the first is less that the second: 11 11
Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com
%d bloggers like this: