Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          references/min-max-1.cc - Use of a const reference in the vector_min_max function (alread encountered in this lecture).Lecture 2 - slide 16 : 29
Program 3

// Using a const reference as an alternative to a call-by-value parameter (avoids copying large objects).
// This is a real-world scenario - in contrast to some of the previous examples.

#include <iostream>    
#include <string>
#include <vector>

// Assume as precondition that vec holds at least one element.
// In this version vec is pass by const reference, which is more efficient than 
// passing it by value (and by a copy).
void vector_min_max(const 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;
}