Search element in a sequence with algorithm find - C++ STL Algorithm

C++ examples for STL Algorithm:find

Description

Search element in a sequence with algorithm find

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <vector> // vector class-template definition 
#include <iterator> 
using namespace std; 

int main() /*from  w w w.  ja va2s .  c om*/
{ 
   const int SIZE = 10; 
   int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; 
   vector< int > v( a, a + SIZE ); // copy of a 
   ostream_iterator< int > output( cout, " " ); 

   cout << "Vector v contains: "; 
   copy( v.begin(), v.end(), output ); // display output vector 

   // locate first occurrence of 16 in v 
   vector< int >::iterator location; 
   location = find( v.begin(), v.end(), 16 ); 

    if ( location != v.end() ) // found 16 
       cout << "\n\nFound 16 at location " << ( location - v.begin() ); 
   else // 16 not found 
       cout << "\n\n16 not found"; 

   // locate first occurrence of 100 in v 
   location = find( v.begin(), v.end(), 100 ); 

    if ( location != v.end() ) // found 100 
       cout << "\nFound 100 at location " << ( location - v.begin() ); 
   else // 100 not found 
       cout << "\n100 not found"; 

}

Result


Related Tutorials