0

Есть две функции. 1-ая сортирует список по char, а 2-ая по int, но у них разные имена. Подскажите как правильно перегрузить функции.

//sort by char
void List::SortByChar()
{
    Listnode *current = head; //вспомогательный указатель.  
    Listnode *next = nullptr; //вспомогательный указатель.  

    if (head == NULL)
        return;
    else {
        while (current->next != NULL) {
            next = current->next;

            do {                
                if (strcmp(current->name, next->name) > 0) {
                std::swap(current->name, next->name);
                std::swap(current->age, next->age);
                }
                next = next->next;
            } while (next != NULL);
            current = current->next;
        }
    }       
}

//sort by int
void List::sortByInt()
{
    Listnode *current = head; //вспомогательный указатель.  
    Listnode *next = nullptr; //вспомогательный указатель.  

    if (head == NULL)
        return;
    else {
        while (current->next != NULL) {
            next = current->next;

            do {                    
                if (current->age > next->age) {
                    std::swap(current->name, next->name);
                    std::swap(current->age, next->age);
                }
                next = next->next;
            } while (next != NULL);
            current = current->next;
        }
    }       
}

2 ответа 2

1

У вас все совершенно одинаково кроме одной строчки. Я бы добавил функцию сравнения, которую передавал единой функции сортировки в качестве параметра.

Типа

static bool Listnode::cmpname(Listnode*a, Listnode*b)
{
    return strcmp(a->name, b->name) > 0;
}

static bool Listnode::cmpage(Listnode*a, Listnode*b)
{
    return a->age > b->age;
}

typedef bool (*cmpfunc)(Listnode*, Listnode*);

void List::SortBy(cmpfunc)
{
    Listnode *current = head; //вспомогательный указатель.  
    Listnode *next = nullptr; //вспомогательный указатель.  

    if (head == NULL)
        return;
    else {
        while (current->next != NULL) {
            next = current->next;

            do {                
                if (cmpfunc(current,name)) {
                std::swap(current->name, next->name);
                std::swap(current->age, next->age);
                }
                next = next->next;
            } while (next != NULL);
            current = current->next;
        }
    }       
}

Аналог SortByInt при этом -

list.SortBy(cmpage);

а SortByChar -

list.SortBy(cmpname);

Более того, в List::SortBy() можно передавать лямбда-выражения, скажем

list.SortBy([](Listnode*a, Listnode*b){ return a->age > b->age; });
6
  • как я понял сделать единую функцию с параметром, а что я должен сравнить?
    – user207147
    3 дек 2016 в 19:12
  • Сравнивает этот параметр - это функция сравнения.
    – Harry
    3 дек 2016 в 19:12
  • а какие параметры я должен написать в функцию sortBy что-то я не понимаю. Для студента это как-то трудновато
    – user207147
    3 дек 2016 в 19:33
  • Вы просто передаете функцию, которая будет вызвана для сравнения. Я написал в ответе, и как написать такие функции, и как их передать в метод сортировки. Функция сравнивает два Listnode так, как это нужно вам - по имени, возрасту, в любом порядке. Вы просто говорите - когда надо будет сравнить два узла - вызови для этого ту функцию, что я указал.
    – Harry
    3 дек 2016 в 19:39
  • понял, спасибо за помощь и понимаине
    – user207147
    3 дек 2016 в 19:43
0

Я решил поупражняться в написании кода на C++, и вот что у меня получилось в контексте вашего вопроса. Я опирался на ваш предыдущий вопрос, где вы привели определение структуры списка и некоторых его методов.

#include <iostream>
#include <cstring>
#include <utility>
#include <initializer_list>

class List
{
public:
    enum SortType { SortByName, SortByAge };
    typedef std::pair<const char *, unsigned int> Human;

public:
    List() = default;
    List(const List &) = delete;
    List & operator =(const List &) = delete;
    ~List()
    {
        while (head)
        {
            Person *tmp = head;
            head = head->next;
            delete[] tmp->name;
            delete tmp;
        }
    }

    void push(const char *name, unsigned int age)
    {
        push({ name, age });
    }

    void push(const Human &h )
    {
        char *s = new char[std::strlen(h.first) + 1];
        std::strcpy(s, h.first);
        head = new Person{ s, h.second, head };
    }

    std::ostream & show(std::ostream &os = std::cout) const
    {
        for (Person *current = head; current; current = current->next)
        {
            os << current->name << ' ' << current->age << std::endl;
        }

        return os;
    }

    void sort(SortType type = SortByName)
    {
        bool ( *order_by[2] )( const Human &, const Human & ) =
        {

            []( const Human &h1, const Human &h2)
            {
                int res = std::strcmp(h1.first, h2.first);
                return res < 0 || (res == 0 && h1.second < h2.second);
            },
            [](const Human &h1, const Human &h2)
            {
                int res = std::strcmp(h1.first, h2.first);
                return h1.second < h2.second || 
                       ( h1.second == h2.second && res < 0);
            }
        };

        if (type != SortByAge) type = SortByName;

        for (Person *current = head; current; current = current->next)
        {
            for (Person *next = current->next; next; next = next->next)
            {
                if (order_by[type](Human(next->name, next->age),
                    Human(current->name, current->age)))
                {
                    std::swap(current->name, next->name);
                    std::swap(current->age, next->age);
                }
            }
        }
    }

private:
    struct Person
    {
        const char *name;
        unsigned int age;
        Person *next;
    };

    Person *head = nullptr;
};

int main()
{
    List lst;

    for (const auto &h : std::initializer_list<List::Human>( 
    { 
        { "Petr", 21 }, 
        { "Ann", 26 }, 
        { "Bob", 24 },
        { "Kate", 24 }
    } ) )
    {
        lst.push(h);
    }

    lst.show() << std::endl;

    lst.sort();

    lst.show() << std::endl;

    lst.sort(List::SortByAge);

    lst.show() << std::endl;
}

Вывод программы на консоль выглядит следующим образом:

Kate 24
Bob 24
Ann 26
Petr 21

Ann 26
Bob 24
Kate 24
Petr 21

Petr 21
Bob 24
Kate 24
Ann 26

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.