Users Online

· Guests Online: 37

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

adjacent_find() Function in C++

adjacent_find() Function in C++

 

 

This C++ program demonstrates the adjacent_find() algorithm. The adjacent_find takes iterator to the beginning and end of a container and an optional predicate as third parameter. The program uses function adjacent_find() to find adjacent pair of elements in which both the elements are same or satisfy boolean true for a predicate passed as a parameter.

 

Here is the source code of the C++ program which demonstrates the adjacent_find() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate adjacent_find algorithm on string vector
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <functional>
  7. #include <vector>
  8. #include <iomanip>
  9. using namespace std;
  10.  
  11. void print(int a[], int len)
  12. {
  13.     for(int i = 0; i < len; i++)
  14.     {
  15.         cout << setw(2) <<  a[i] << " ";
  16.     }
  17.     cout << endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     int a[] = {1, 2, 3, 3, 5, 6, 6, 3};
  23.     int alen = sizeof(a) / sizeof(int);
  24.     int * ii = a, * ij = a;
  25.  
  26.     cout << "Array : ";
  27.     print(a, alen);
  28.     // Finding without use of predicates
  29.     cout << "Pairwise elements (a, b) where a == b : ";
  30.     while(ii <= a + alen)
  31.     {
  32.         ii = adjacent_find(ii, a + alen);
  33.         if(ii != a + alen)
  34.             cout << "(" << *ii << ", " << *(ii + 1) << ") ";
  35.         ii = ii + 2;
  36.     }
  37.     cout << endl;
  38.     // Finding with use of predicates
  39.     sort(a, a + alen, greater<int>());
  40.     cout << "Pairwise elements (a, b) where a >= b : ";
  41.     while(ij <= a + alen)
  42.     {
  43.         ij = adjacent_find(ij, a + alen, greater_equal<int>());
  44.         if(ij != a + alen)
  45.             cout << "(" << *ij << ", " << *(ij + 1) << ") ";
  46.         ij = ij + 2;
  47.     }
  48.     cout << endl;
  49. }

 

$ a.out
Array :  1  2  3  3  5  6  6  3
Pairwise elements (a, b) where a == b : (3, 3) (6, 6)
Pairwise elements (a, b) where a >= b : (6, 6) (5, 3) (3, 3) (2, 1)

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.64 seconds
10,255,294 unique visits