C++/STL Algorithms Non modifying sequence operations/find

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrating generic find algorithm with an array

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm> // for find

using namespace std; int main() {

 char s[] = "C++ is a better C";
 int len = strlen(s);
 // Search for the first occurrence of the letter e:
 const char* where = find(&s[0], &s[len], "e");
 cout << *where<< endl;
 where = find(&s[0], &s[len], "A");
 cout << *where<< endl;
 return 0;

} /* e

*/        
   
 </source>


find and display sorted v in highest 20th percentile

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>
  4. include <vector>

using namespace std; int main( ) {

  const int a[] = { 8, 7, 4, 9, 5, 2, 6, 2, 7,9, };
  const int len = sizeof( a ) / sizeof( a[0] );
  const int percentile_20 = static_cast<int>( 0.2 * len );
  vector<int> v( a, a+len );
  copy( a, a+len, v.begin() );
  partial_sort( v.begin(), v.begin()+percentile_20,v.end(), greater<int>() );
  copy( v.begin(), v.begin()+percentile_20,ostream_iterator<int>( cout, " " ) );

}


 </source>


find and display sorted v in lowest 20th percentile

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>
  4. include <vector>

using namespace std; int main( ) {

  const int a[] = { 8, 7, 4, 9, 5, 2, 6, 2, 7,9, };
  const int len = sizeof( a ) / sizeof( a[0] );
  const int percentile_20 = static_cast<int>( 0.2 * len );
  vector<int> v( a, a+len );
  copy( a, a+len, v.begin() );
  partial_sort( v.begin(), v.begin()+percentile_20,v.end() );
  copy( v.begin(), v.begin()+percentile_20,ostream_iterator<int>( cout, " " ) );

}


 </source>


find and display v in highest 20th percentile

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>
  4. include <vector>

using namespace std; int main( ) {

  const int a[] = { 8, 7, 4, 9, 5, 2, 6, 2, 7,9, };
  const int len = sizeof( a ) / sizeof( a[0] );
  const int percentile_20 = static_cast<int>( 0.2 * len );
  vector<int> v( a, a+len );
  copy( a, a+len, v.begin() );
  nth_element( v.begin(), v.begin()+percentile_20-1,v.end(), greater<int>() );
  copy( v.begin(), v.begin() + percentile_20,ostream_iterator<int>( cout, " " ) );

}


 </source>


find and display v in lowest 20th percentile

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>
  4. include <vector>

using namespace std; int main( ) {

  const int a[] = { 8, 7, 4, 9, 5, 2, 6, 2, 7,9, };
  const int len = sizeof( a ) / sizeof( a[0] );
  const int percentile_20 = static_cast<int>( 0.2 * len );
  vector<int> v( a, a+len );
  nth_element( v.begin(), v.begin()+percentile_20-1,v.end() );
  copy( v.begin(), v.begin() + percentile_20,ostream_iterator<int>( cout, " " ) );

}


 </source>


find an element in a list

<source lang="cpp">

//erase an element in a list //Combine erase and remove to remove a found element

  1. include <iostream>
  2. include <string>
  3. include <list>
  4. include <algorithm>
  5. include <functional>

using namespace std; int main( ) {

  list<string> lstStr;
  lstStr.push_back("A");
  lstStr.push_back("B");
  lstStr.push_back("C");
  lstStr.push_back("D");
  lstStr.push_back("E");
  list<string>::iterator p;
  p = find(lstStr.begin( ), lstStr.end( ), "C");
  p = lstStr.erase(p);
  lstStr.erase(remove(lstStr.begin( ), lstStr.end( ), "D"),lstStr.end( ));

}


 </source>


Find the maximum element in a range in a list

<source lang="cpp">

/* The following code example is taken from the book

* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
  1. include <iostream>
  2. include <list>
  3. include <algorithm>

using namespace std; int main() {

   list<int> coll;
   list<int>::iterator pos;
   // insert elements from 20 to 40
   for (int i=20; i<=40; ++i) {
       coll.push_back(i);
   }
   /* find position of element with value 3
    * - there is none, so pos gets coll.end()
    */
   pos = find (coll.begin(), coll.end(),    // range
               3);                          // value
   
   /* reverse the order of elements between found element and the end
    * - because pos is coll.end() it reverses an empty range
    */
   reverse (pos, coll.end());
   // find positions of values 25 and 35
   list<int>::iterator pos25, pos35;
   pos25 = find (coll.begin(), coll.end(),  // range
                 25);                       // value
   pos35 = find (coll.begin(), coll.end(),  // range
                 35);                       // value
   /* print the maximum of the corresponding range
    * - note: including pos25 but excluding pos35
    */
   cout << "max: " << *max_element (pos25, pos35) << endl;
   // process the elements including the last position
   cout << "max: " << *max_element (pos25, ++pos35) << endl;

} /* max: 34 max: 35

*/
       
   
 </source>


Generic find algorithm: use find function to find an element in an array

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <list>
  5. include <iterator>

using namespace std; int main() {

 int a[10] = {12, 3, 25, 7, 11, 213, 7, 123, 29, -31};
 // Find the first element equal to 7 in the array:
 int* ptr = find(&a[0], &a[10], 7);
 assert (*ptr == 7 && *(ptr+1) == 11);
 cout << *ptr;
 return 0;

} /* 7

*/        
   
 </source>


Generic find algorithm with input iterators associated with io streams

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <list>
  5. include <iterator>

using namespace std; int main() {

 cout << "Type some characters, including an "x" followed\n"
   << "by at least one nonwhite-space character: " << flush;
 istream_iterator<char> in(cin);
 istream_iterator<char> eos;
 find(in, eos, "x");
 cout << "The first nonwhite-space character following\n"
      << "the first "x" was "" << *(++in) << ""." << endl;
 
 return 0;

}

/* 

Type some characters, including an "x" followed by at least one nonwhite-space character: x is before y The first nonwhite-space character following the first "x" was "i".

*/       
   
 </source>


Locate first occurrence of a value in a vector

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <algorithm>
  2. include <vector>
  3. 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

*/
       
   
 </source>


Use assert to check the find method

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <list>
  5. include <iterator>

using namespace std; int main() {

 int a[10] = {12, 3, 25, 7, 11, 213, 7, 123, 29, -31};
 // Find the first element equal to 7 in the array:
 int* ptr = find(&a[0], &a[10], 7);
 assert (*ptr == 7 && *(ptr+1) == 11);
 cout << *ptr;
 return 0;

} /* 7

*/
       
   
 </source>


Use find algorithm to find an element in a list

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <list>
  5. include <iterator>

using namespace std; int main() {

 int a[10] = {12, 3, 25, 7, 11, 213, 7, 123, 29, -31};
 list<int> list1(&a[0], &a[10]);
 // Find the first element equal to 7 in list1:
 list<int>::iterator i = find(list1.begin(),list1.end(),7);
 assert (*i == 7 && *(++i) == 11);
 cout << *i;
 return 0;

} /* 11

*/
       
   
 </source>


Use find to search an element in a container

<source lang="cpp">


/* The following code example is taken from the book

* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
  1. include <iostream>
  2. include <vector>
  3. include <deque>
  4. include <list>
  5. include <set>
  6. include <map>
  7. include <string>
  8. include <algorithm>
  9. include <iterator>
  10. include <functional>
  11. include <numeric>

/* PRINT_ELEMENTS()

* - prints optional C-string optcstr followed by
* - all elements of the collection coll
* - separated by spaces
*/

template <class T> inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="") {

   typename T::const_iterator pos;
   std::cout << optcstr;
   for (pos=coll.begin(); pos!=coll.end(); ++pos) {
       std::cout << *pos << " ";
   }
   std::cout << std::endl;

} /* INSERT_ELEMENTS (collection, first, last)

* - fill values from first to last into the collection
* - NOTE: NO half-open range
*/

template <class T> inline void INSERT_ELEMENTS (T& coll, int first, int last) {

   for (int i=first; i<=last; ++i) {
       coll.insert(coll.end(),i);
   }

}

using namespace std; int main() {

   list<int> coll;
   INSERT_ELEMENTS(coll,1,9);
   INSERT_ELEMENTS(coll,1,9);
   PRINT_ELEMENTS(coll,"coll: ");
   // find first element with value 4
   list<int>::iterator pos1;
   pos1 = find (coll.begin(), coll.end(),    // range
                4);                          // value
   /* find second element with value 4
    * - note: continue the search behind the first 4 (if any)
    */
   list<int>::iterator pos2;
   if (pos1 != coll.end()) {
       pos2 = find (++pos1, coll.end(),      // range
                    4);                      // value
   }
   /* print all elements from first to second 4 (both included)
    * - note: now we need the position of the first 4 again (if any)
    * - note: we have to pass the position behind the second 4 (if any)
    */
   if (pos1!=coll.end() && pos2!=coll.end()) {
       copy (--pos1, ++pos2,
             ostream_iterator<int>(cout," "));
       cout << endl;
   }

} /* coll: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 4

*/
       
   
 </source>


Use istream_iterator and find

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <list>
  5. include <iterator>

using namespace std; int main() {

 cout << "Type some characters, including an "x" followed\n"
   << "by at least one nonwhite-space character: " << flush;
 istream_iterator<char> in(cin);
 istream_iterator<char> eos;
 find(in, eos, "x");
 cout << "The first nonwhite-space character following\n"
      << "the first "x" was "" << *(++in) << ""." << endl;
 return 0;

}

/* 

Type some characters, including an "x" followed by at least one nonwhite-space character: x is after y The first nonwhite-space character following the first "x" was "i".

*/       
   
 </source>


Using find with normal iteration

<source lang="cpp">

  1. include <iostream>
  2. include <vector>
  3. include <algorithm> // for find
  4. include <iterator>

using namespace std;

int main() {

 string s("It is him.");
 vector<char> vector1(s.begin(), s.end());
 ostream_iterator<char> out(cout, " ");
 vector<char>::iterator i = find(vector1.begin(), vector1.end(), "i");
 cout << "chars from the first i to the end: ";
 copy(i, vector1.end(), out); cout << endl;
 return 0;

} /* chars from the first i to the end: i s h i m .

*/        
   
 </source>