references/min-max.cc - A typical use of references: A number of results passed back from vector_min_max via references. | Lecture 2 - slide 15 : 29 Program 3 |
// Illustrates the use of references for output parameters. #include <iostream> #include <string> #include <vector> // Return the minimum, index og min, maximum, and index of maximum via reference parameters. // Assume as precondition that vec holds at least one element. // In this version vec is pass by value. Better alternative: const reference. void vector_min_max(std::vector<double> vec, double& min, int& min_index, double& max, int& max_index){ double cur_max{vec[0]}, cur_min{vec[0]}; int cur_min_index{0}, cur_max_index{0}; for(int i = 0; i < vec.size(); ++i){ if (vec[i] > cur_max){ cur_max = vec[i]; cur_max_index = i; } if (vec[i] < cur_min){ cur_min = vec[i]; cur_min_index = i; } } min = cur_min; max = cur_max; min_index = cur_min_index; max_index = cur_max_index; } int main () { using namespace std; vector<double> v{1.1, -3.5, 7, 9, 0, -0.5}; double mi, ma; int i_mi, i_ma; vector_min_max(v, mi, i_mi, ma, i_ma); cout << "Min: " << mi << " at: " << i_mi << endl; cout << "Max: " << ma << " at: " << i_ma << endl; }