C++ Tutorial/STL Algorithms Non modifying sequence operations/find — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Версия 17:21, 25 мая 2010

Define == operator in order to use the find method

<source lang="cpp">#include <iostream>

  1. include <vector>
  2. include <algorithm>
  3. include <string>

using namespace std;

class Employee {

 string name;
 unsigned number;

public:

 Employee() { name = ""; number = 0; }
 Employee(string n, unsigned num) {
   name = n;
   number = num;
 }
 string get_name() { return name; }
 unsigned get_number() { return number; }

}; void show(vector<Employee> vect) {

 vector<Employee>::iterator itr;
 for(itr=vect.begin(); itr != vect.end(); ++itr)
   cout << itr->get_number() << " " << itr->get_name() << endl;;

} bool operator==(Employee a, Employee b){

 return a.get_number() == b.get_number();

} int main() {

 vector<Employee> employeeList;
 employeeList.push_back(Employee("A", 9));
 employeeList.push_back(Employee("B", 8));
 employeeList.push_back(Employee("C", 6));
 employeeList.push_back(Employee("D", 1));
 show(employeeList);
 vector<Employee>::iterator itr;
 itr = find(employeeList.begin(), employeeList.end(), Employee("", 2));
 cout << itr->get_name();
 return 0;

}</source>

Demonstrating generic find algorithm with an array

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. 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;

}</source>

e

Find an Element and Its Position in a Vector

<source lang="cpp">#include <iostream>

  1. include <vector>
  2. include <algorithm>

using namespace std; int main () {

  vector <int> v;
  v.push_back (50);
  v.push_back (2991);
  v.push_back (23);
  v.push_back (9999);
  vector <int>::iterator i = v.begin ();
  while (i != v.end ()){
      cout << *i << endl;
      ++ i;
  }
  i = find (v.begin (),v.end (), 2991);
  if (i != v.end ())
  {
      int nPosition = distance (v.begin (), i);
      cout << "Value "<< *i;
      cout << " found in the vector at position: " << nPosition << endl;
  }
  return 0;

}</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 a value in vector

<source lang="cpp">#include <algorithm>

  1. include <vector>
  2. include <iostream>

using namespace std; int main(int argc, char** argv) {

 int num = 4;
 vector<int> myVector;
 myVector.push_back(1);
 myVector.push_back(2);
 myVector.push_back(3);
 myVector.push_back(4);
 vector<int>::iterator it = find(myVector.begin(), myVector.end(), num);
 if (it == myVector.end()) {
     cout << "Could not find " << num << endl;
 } else {
     cout << "Found " << *it << endl;
 }
 
 return (0);

}</source>

Find empty string

<source lang="cpp">#include <functional>

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

using namespace std; void findEmptyString(const vector<string>& strings) {

 vector<string>::const_iterator it = find_if(strings.begin(), strings.end(),mem_fun_ref(&string::empty));
 if (it == strings.end()) {
   cout << "No empty strings!\n";
 } else {
   cout << "Empty string at position: " << it - strings.begin() << endl;
 }

} int main(int argc, char** argv) {

 vector<string> myVector;
 string one = "blah";
 string two = "";
 myVector.push_back(one);
 myVector.push_back(one);
 myVector.push_back(two);
 myVector.push_back(one);
 findEmptyString(myVector);
 return (0);

}</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;

}</source>

max: 34
max: 35

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

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. include <algorithm>
  3. include <list>
  4. 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;

}</source>

7"

Generic find algorithm with input iterators associated with io streams

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. include <algorithm>
  3. include <list>
  4. 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;

}</source>

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".

Locate first occurrence of a value in a vector

<source lang="cpp">#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;

}</source>

Vector v contains: 10 2 17 5 16 8 13 11 20 7
Found 16 at location 4

Use assert to check the find method

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. include <algorithm>
  3. include <list>
  4. 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;

}</source>

7

Use find algorithm to find an element in a list

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. include <algorithm>
  3. include <list>
  4. 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;

}</source>

11"

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;
   }

}</source>

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

Use istream_iterator and find

<source lang="cpp">#include <iostream>

  1. include <cassert>
  2. include <algorithm>
  3. include <list>
  4. 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;

}</source>

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".

Using find with normal iteration

<source lang="cpp">#include <iostream>

  1. include <vector>
  2. include <algorithm> // for find
  3. 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;

}</source>

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