Locate first occurrence of a value in a vector : find « STL Algorithms Non modifying sequence operations « C++






Locate first occurrence of a value in a vector

  
 

#include <iostream>
using std::cout;
using std::endl;

#include <algorithm>
#include <vector>
#include <iterator>

int main()
{
   int a[ 10 ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 };
   std::vector< int > v( a, a + 10 ); // copy of a
   std::ostream_iterator< int > output( cout, " " );

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

   std::vector< int >::iterator location;
   location = std::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";

   cout << endl;
   return 0;
}
/* 
Vector v contains: 10 2 17 5 16 8 13 11 20 7

Found 16 at location 4

 */
        
    
  








Related examples in the same category

1.Use find to search an element in a container
2.find an element in a list
3.Find the maximum element in a range in a list
4.Using find with normal iteration
5.Demonstrating generic find algorithm with an array
6.Generic find algorithm: use find function to find an element in an array
7.Use find algorithm to find an element in a list
8.Use istream_iterator and find
9.Generic find algorithm with input iterators associated with io streams
10.Use assert to check the find method
11.find and display v in lowest 20th percentile
12.find and display v in highest 20th percentile
13.find and display sorted v in lowest 20th percentile
14.find and display sorted v in highest 20th percentile