Есть массив, заполненный действительными числами. Реализовать функцию сортировки массива по убыванию 2 методами.Построить меню выбора сортировки

Выдаёт ошибку: не найден оператор, принимающий правый операнд типа void. Ошибка в строке: cout << f(a,n) << “ “ << “\t”;


#include <iostream>
#include <conio.h>
using namespace std;

typedef void(*TFunc)(double* a, int n);
void bubblesort(double* a, int n);
void vibor(double* a, int n);
void sort(double* a, int n, TFunc f);

TFunc menu();

int main()
{
    setlocale(LC_ALL, "ru");
    TFunc item;
    int n;
    cout << "Enter the amount of elements in array --> " << endl;
    cin >> n;
    double* a = new double[n];
    cout << "Array before selecting a way to sort:\n";
    for (int i = 0; i < n; i++)
    {
        cout << i + 1 << "-ый элемент: ";
        cin >> a[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;

    item = menu();
    if (item == NULL)
    {
        cout << "Functioт number is entered incorrectly!";
    }
    else
    {
        sort(a, n, item);
    }
    delete[] a;
    system("pause");
    cout << "\nPress any key to exit.\n";
    _getch();
}

void bubblesort(double* a, int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (a[j] < a[j + 1])
            {
                double temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}
void vibor(double* a, int n)
{
    for (int i = 0; i < n - 1; i++)
    {
        int biggestIndex = i;
        for (int j = i + 1; j < n; j++)
        {
            if (a[j] > a[biggestIndex])
            {
                biggestIndex = j;
            }
        }
        swap(a[i], a[biggestIndex]);
    }
}

void sort(double* a, int n, TFunc f)
{
    for (int i = 0; i < n; i++)
    {
        cout << f(a, n) << " " << "\t";
    }
    cout << endl;
}

TFunc menu()
{
    TFunc fun_items[] = { bubblesort, vibor };
    int key;
    cout << "Selecting a way to sort array:\n"
        "1 - bubblesort, 2 - vibor\n";
    cin >> key;
    switch (key)
    {
    case 1:;
    case 2: return fun_items[key - 1];
    default: return NULL;
    }
}


Ответы (2 шт):

Автор решения: DmitryK

Должно быть как-то так:

void sort(double* a, int n, TFunc f)
{
    f(a, n); // выполняем сортировку массива
    for (int i = 0; i < n; i++)  // выводим массив в поток
    {
        cout << a[i] << "\t";
    }
    cout << endl;
}

Потому что в Вашем варианте вы пытаетесь вывести в поток возвращаемое значение функции. А функция не возвращает ничего, т.к. void bubblesort(). И перегруженного оператора вывода в поток для типа void не существует (выводить нечего). Поэтому и ошибка.

→ Ссылка
Автор решения: Harry

Чтоб выводить результат именно с помощью

cout << f(a, n);

(кстати, зачем это делать n раз в цикле?!), можно пойти таким путем:

#include <iostream>

using namespace std;

typedef pair<double*,int>(*TFunc)(double* a, int n);


pair<double*,int> bubblesort(double* a, int n);
pair<double*,int> vibor(double* a, int n);
void sort(double* a, int n, TFunc f);

ostream& operator<< (ostream& os, const pair<double*,int>& p)
{
    for(int i = 0; i < p.second; ++i)
        os << p.first[i] << "\t";
    return os << endl;
}

TFunc menu();

int main()
{
    TFunc item;
    int n;
    cout << "Enter the amount of elements in array --> " << endl;
    cin >> n;
    double* a = new double[n];
    cout << "Array before selecting a way to sort:\n";
    for (int i = 0; i < n; i++)
    {
        cout << i + 1 << "-ый элемент: ";
        cin >> a[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;

    item = menu();
    if (item == NULL)
    {
        cout << "Function number is entered incorrectly!";
    }
    else
    {
        sort(a, n, item);
    }
    delete[] a;
}

pair<double*,int> bubblesort(double* a, int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (a[j] < a[j + 1])
            {
                double temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
    return make_pair(a,n);
}

pair<double*,int> vibor(double* a, int n)
{
    for (int i = 0; i < n - 1; i++)
    {
        int biggestIndex = i;
        for (int j = i + 1; j < n; j++)
        {
            if (a[j] > a[biggestIndex])
            {
                biggestIndex = j;
            }
        }
        swap(a[i], a[biggestIndex]);
    }
    return make_pair(a,n);
}

void sort(double* a, int n, TFunc f)
{
    cout << f(a, n);
}

TFunc menu()
{
    TFunc fun_items[] = { bubblesort, vibor };
    int key;
    cout << "Selecting a way to sort array:\n"
        "1 - bubblesort, 2 - vibor\n";
    cin >> key;
    switch (key)
    {
    case 1:;
    case 2: return fun_items[key - 1];
    default: return NULL;
    }
}

См. https://ideone.com/CEWjEK

Но, конечно, это извращение :)

→ Ссылка