C++ Function Return Returning a pointer from a Function

Description

C++ Function Return Returning a pointer from a Function

#include <iostream>
#include <iomanip>
#include <string>
using std::string;

void show_data(const double data[], int count = 1, const  string& title = "Data Values",
                                                      int width = 10, int perLine = 5);
const double* largest(const double data[], int count);
const double* smallest(const double data[], int count);
double* shift_range(double data[], int count, double delta);
double* scale_range(double data[], int count, double divisor);
double* normalize_range(double data[], int count);

int main() {//from w w w .j  av a 2  s.c  om
  double samples[] { 1.0, 3.0, 6.0,  4.0, 7.0, 6.0, 7.0,  8.0, 9.0, 10.0,21.0, 12.0 };

  const int count{sizeof (samples) / sizeof (samples[0])};   // Number of samples
  show_data(samples, count, "Original Values");                 // Output original values
  normalize_range(samples, count);                              // Normalize the values
  show_data(samples, count, "Normalized Values", 12);           // Output normalized values
}

// Finds the largest of an array of double values
const double* largest(const double data[], int count)
{
  int index_max {};
  for (int i {1} ; i < count ; ++i)
    if (data[index_max] < data[i])
      index_max = i;
  return &data[index_max];
}

// Finds the smallest of an array of double values
const double* smallest(const double data[], int count)
{
  int index_min{};
  for (int i {1} ; i < count ; ++i)
    if (data[index_min] > data[i])
      index_min = i;

  return &data[index_min];
}

// Modify a range of value by delta
double* shift_range(double data[], int count, double delta)
{
  for (int i {} ; i < count ; ++i)
    data[i] += delta;
  return data;
}

// Scale an array of values by divisor
double* scale_range(double data[], int count, double divisor)
{
  if (!divisor) return data;                          // Do nothing for a zero divisor

  for (int i {} ; i < count ; ++i)
    data[i] /=divisor;
  return data;
}

// Normalize an array of values to the range 0 to 1
double* normalize_range(double data[], int count)
{
  return scale_range(shift_range(data, count, -(*smallest(data, count))),
    count, *largest(data, count));
}

// Outputs an array of double values
void show_data(const double data[], int count, const string& title, int width, int perLine)
{
  std::cout << title << std::endl;                    // Display the title

  // Output the  data values
  for (int i {} ; i < count ; ++i)
  {
    std::cout << std::setw(width) << data[i];         // Display  a data item
    if ((i + 1) % perLine == 0)                       // Newline after perline values
      std::cout << std::endl;
  }
  std::cout << std::endl;
}



PreviousNext

Related