double P[5] = {9, 17, 151, -3, 5};
I need to sort this array with help of pointers in ascending order by cosines of array elements.
double P[5] = {9, 17, 151, -3, 5};
I need to sort this array with help of pointers in ascending order by cosines of array elements.
#include <array>
#include <algorithm> // std::sort
#include <cmath> // cos() // cosine function
#include <iostream>
// short function to print a std::array, T must have << operator
template <typename T, std::size_t N>
void printArray(const std::array<T, N>& arr)
{
for (auto i: arr)
std::cout << i << ' ';
std::cout << '\n';
}
int main()
{
std::array<double, 5> P{9, 17, 151, -3, 5};
printArray(P);
// Passing a lambda to std::sort so it compares cosines of the values
std::sort(P.begin(),
P.end(),
[](double a, double b) { return cos(a) < cos(b); });
printArray(P);
}
Instead of a C-array, I am using the std::array
library (C++11). It provides more safety. Since sorting is something that's so common, the C++ standard library provides a function for it, and we can tell it how to compare the values. I do that by passing the lambda as the third argument.
If you really want/have to use a C array, the code doesn't change much.
#include <algorithm> // std::sort
#include <cmath> // cos() // cosine function
#include <iostream>
#include <iterator>
// short function to print a std::array, T must have << operator
template <typename T>
void printArray(T *arr, int size)
{
for (int i = 0; i < size; ++i)
std::cout << arr[i] << ' ';
std::cout << '\n';
}
int main()
{
double P[5] = {9, 17, 151, -3, 5};
printArray(P, sizeof(P) / sizeof(double));
// Passing a lambda to std::sort so it compares cosines of the values
std::sort(std::begin(P),
std::end(P),
[](double a, double b) { return cos(a) < cos(b); });
printArray(P, sizeof(P) / sizeof(double));
}