Demonstrating Functions sort and binary_search

Figure 7.18 begins by creating an unsorted array of strings (lines 13–14) and displaying the contents of the array (lines 17–19). Next, line 21 uses C++ Standard Library function sort to sort the elements of the array colors into ascending order. The sort function’s arguments specify the range of elements that should be sorted—in this case, the entire array. We’ll discuss the complete details of class template array’s begin and end functions in later chapters. As you’ll see, function sort can be used to sort the elements of several different types of data structures. Lines 24–26 display the contents of the sorted array.


 1   // Fig. 7.18: fig07_18.cpp
 2   // Sorting and searching arrays.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <array>
 6   #include <string>
 7   #include <algorithm> // contains sort and binary_search
 8   using namespace std;
 9
10   int main()
11   {
12      const size_t arraySize = 7; // size of array colors
13      array< string, arraySize > colors = { "red", "orange", "yellow",
14         "green", "blue", "indigo", "violet" };
15
16      // output original array
17      cout << "Unsorted array: ";
18      for ( string color : colors )
19         cout << color << " ";
20
21      sort( colors.begin(), colors.end() ); // sort contents of colors
22
23      // output sorted array
24      cout << " Sorted array: ";
25      for ( string item : colors )
26         cout << item << " ";
27
28      // search for "indigo" in colors
29      bool found = binary_search( colors.begin(), colors.end(), "indigo" );
30      cout << " "indigo" " << ( found ? "was" : "was not" )
31         << " found in colors" << endl;
32
33      // search for "cyan" in colors
34      found = binary_search( colors.begin(), colors.end(), "cyan" );
35      cout << ""cyan" " << ( found ? "was" : "was not" )
36         << " found in colors" << endl;
37   } // end main


Unsorted array:
red orange yellow green blue indigo violet
Sorted array:
blue green indigo orange red violet yellow

"indigo" was found in colors
"cyan" was not found in colors


Fig. 7.18. Sorting and searching arrays.

Lines 29 and 34 demonstrate use binary_search to determine whether a value is in the array. The sequence of values must be sorted in ascending order first—binary_search does not verify this for you. The function’s first two arguments represent the range of elements to search and the third is the search key—the value to locate in the array. The function returns a bool indicating whether the value was found. In Chapter 16, we’ll use a C++ Standard function find to obtain the location of the search key in an array.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.218.105