Useful Array Functions in C++

The min_element, max_element, sort, random_shuffle, and find functions can be used for arrays.  

C++ provides several functions for manipulating arrays. You can use the min_element and max_element functions to return the pointer to the minimal and maximal element in an array, the sort function to sort an array, the random_shuffle function to randomly shuffle an array, and the find function to find an element in an array. All these functions use pointers in the arguments and in the return value. Listing 11.7 gives an example of using these functions.

Listing 11.7 UsefulArrayFunctions.cpp

1 #include <iostream>
2
#include <algorithm>
3
using namespace std;
4
5
void printArray(const int* list, int size)

6 {
7   
for (int i = 0; i < size; i++)
8    cout << list[i] <<
” “;
9    cout << endl;
10 }
11
12
int main()
13 {
14   
int list[] = {4, 2, 3, 6, 5, 1};
15    printArray(list,
6);
16
17   
int* min = min_element(list, list + 6);
18   
int* max = max_element(list, list + 6);
19    cout <<
“The min value is ” << *min << ” at index ”
20       << (min – list) << endl;
21    cout <<
“The max value is ” << *max << ” at index ”
22       << (max – list) << endl;
23
24    random_shuffle(list, list +
6);
25    printArray(list,
6);
26
27    sort(list, list +
6);
28    printArray(list,
6);
29
30   
int key = 4;
31   
int* p = find(list, list + 6, key);
32   
if (p != list + 6)
33        cout <<
“The value ” << *p << ” is found at position ”
34        << (p – list) << endl;
35   
else
36        cout << “The value ” << *p << ” is not found” << endl;
37
38   
return 0;
39 }

Invoking min_element(list, list + 6) (line 17) returns the pointer for the smallest element in the array from list[0] to list[5]. In this case, it returns list + 5 since value 1 is the smallest element in the array and the pointer to this element is list + 5. Note that the two arguments passed to the function are the pointers that specify a range and the second pointer points the end of the specified range.

Invoking random_shuffle(list, list + 6) (line 24) randomly rearranges the elements in the array from list[0] to list[5].

Invoking sort(list, list + 6) (line 27) sorts the elements in the array from list[0] to list[5].

Invoking find(list, list + 6, key) (line 31) finds the key in the array from list [0] to list[5]. The function returns the pointer that points the matching element in the array if the element is found; otherwise, it returns the pointer that points to the position after the last element in the array (i.e., list + 6 in this case).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *