C ++ - Как отсортировать данные в связанном списке и отобразить его? - PullRequest
0 голосов
/ 07 мая 2018

В настоящее время я работаю над программой, у которой есть связанный список. В моей программе должна быть функция, которая может сортировать все данные по месяцам, а затем отображать все данные, но я не могу найти хороший пример для ссылки, потому что в моем случае мне нужно найти string expireDate;, который вводится таким образом дд / мм / гггг , что означает, что мне нужно взять его подстроку с помощью std::string str2 = temp->expireDate.substr(3,2);, чтобы получить месяц, а затем преобразовать подстроку в целое число с помощью int month;. Пожалуйста, посмотрите на мой код, он отсортирован, но он ничего не показывает, когда я его запускаю, я думаю, что должна быть очень маленькая ошибка. Я уже понял свои ошибки, на самом деле это просто глупая ошибка. Там нет ошибки в этом коде, хотя.

carInsurance* remove_next(carInsurance* prev)// pass NULL if start_ptr is the Node to be removed
{
    if(prev)
    {
        if( prev->next )// ensure prev isn't pointing to the last Node in the list
        {
            carInsurance* temp = prev->next;// temp will be removed
            prev->next = temp->next;// link across temp
            return temp;
        }
    }
    else if(start_ptr)// ensure list not empty
    {
        carInsurance* temp = start_ptr;// start_ptr will be removed
        start_ptr = start_ptr->next;
        return temp;
    }

    return NULL;// if called on empty list, or if prev->next is NULL
}

void carInsurance::sortMonth(int *x) // sort by month in ascending order
{
    carInsurance *start_ptr2 = NULL;// head of sorted list
    float price, addPrice;

    while(start_ptr)// repeat until no nodes left in unsorted list
    {
        // pointers for iterating through the unsorted list
        carInsurance *prev = NULL;// always previous to the current node considered (below)
        carInsurance *curr = start_ptr;// start at beginning of list
        carInsurance *prevMax = NULL;// pointer to node before the node with the highest age
        int max = start_ptr->month;// 1st node holds max age to start

        while(curr)// iterate through the list
        {
            if(curr->month > max )// new highest age found
            {
                max = curr->month;// save new max age
                prevMax = prev;// save pointer to node before the max
            }
            prev = curr;// advance iterators
            curr = curr->next;
        }

        // Node with the highest age found this pass through the list.
        carInsurance *xferNode = remove_next(prevMax);// obtain node to be moved into sorted list
        if( xferNode )// check that it's not NULL
        {
            xferNode->next = start_ptr2;// add to beginning of sorted list
            start_ptr2 = xferNode;
        }
    }
    start_ptr = start_ptr2;// list now sorted. Reassign start_ptr to point to it.

    while(temp != NULL)// Display details for what temp points to
    {
        cout << "\n___Customer Information___\n" << endl;
        cout << "\nName : " << temp->name << endl;
        cout << "IC: "<< temp->iCno << endl;
        cout << "Date of Birth: " << temp->dob << endl;
        cout << "Nationality: " << temp->nationality << endl;
        cout << "Address: " << temp->address << endl;
        cout << "Mobile Number: " << temp->phoneNo << endl;
        cout << "Email: " << temp->email << endl;
        cout << "Occupation: " << temp->occupation << endl;

        cout << "\n_____Car Information_____\n" << endl;
        cout << "Car Plate Number: " << temp->carNo << endl;
        cout << "Insurance Expire Date: " << temp->expireDate << endl;
        cout << "Usage of Car Model/Make: " << temp->carUsage << endl;
        cout << "Manufacturing Date: " << temp->manufacturingDate << endl;

        cout << "\n___Insurance Information___\n" << endl;
        cout << "Insurance Package:" << endl;
        if(temp->package == 1)
        {
            cout << "\nPackage A (Comprehensive Cover)" << endl;
            cout << "\t-Covers losses or damages to your car due to accident, fire and theft    " << endl;
            cout << "\t-Covers Third Party death and bodily injuries                            " << endl;
            cout << "\t-Covers Third Party property losses or damages                           " << endl;
            price = 1000;

        }
        else if (temp->package == 2)
        {
            cout << "\nPackage B (Third Party Cover)" << endl;
            cout << "\t-Covers Third Party death and bodily injuries" << endl;
            cout << "\t-Covers Third Party property losses or damages" << endl;
            price = 1500;
        }
        else if (temp->package == 3)
        {
            cout << "\nPackage C (Third Party, Fire & Theft Cover)" << endl;
            cout << "\t-Covers losses or damages to your car due to fire or theft" << endl;
            cout << "\t-Covers Third Party death and bodily injuries" << endl;
            cout << "\t-Covers Third Party property losses or damages" << endl;
            price = 900;
        }
        else
        cout << "No package available" << endl;

        if(temp->additional == 1)
        {
            cout << "\nAdditional package: "<< endl;
            if (temp->option==1){
                cout << "Road tax renewal" << endl;
                addPrice = 50;
            }

            else if (temp->option==2){
                cout << "Name of second driver" << endl;
                addPrice = 0;
            }

            else if (temp->option==3){
                cout << "Windscreen coverage" << endl;
                addPrice = 20;
            }

            else if (temp->option==4){
                cout << "Rental reimbursement" << endl;
                addPrice = 50;
            }

            else if (temp->option==5){
                cout << "Roadside assistance or towing insurance" << endl;
                addPrice = 80;
            }

            else if (temp->option==6){
                cout << "Full glass coverage" << endl;
                addPrice = 70;
            }
            else
                cout << "Not availabe"<< endl;
            }
            else{
                cout << "No additional package" << endl;
                price = 0;
            }
            temp->insuranceAmount = price + addPrice;
            cout << "Amount to be insured: RM" << temp->insuranceAmount << endl;

            //temp = temp->next;
            }//End of While Loop
}//End of sortMonth

1 Ответ

0 голосов
/ 07 мая 2018

Вам разрешено использовать весь C ++ или вам действительно разрешено использовать C только с std :: string и std :: cout?

Если вы можете использовать C ++, то вот как я бы это сделал (все еще используя связанный список, поскольку вы указали, что в вашем вопросе std :: vector и std :: sort будут более производительными, если вам не нужно использовать связанный список):

#include <iostream>
#include <sstream>
#include <iterator>
#include <locale>
#include <vector>
#include <list>

// define a facet that adds slash to the list of delimiters
class slash_is_space : public std::ctype<char> {
public:
    mask const *get_table() { 
        static std::vector<std::ctype<char>::mask> 
            table(classic_table(), classic_table()+table_size);
        table['/'] = (mask)space;
        return &table[0];
    }
    slash_is_space(size_t refs=0) : std::ctype<char>(get_table(), false, refs) { }
};

// define a class (with public members) that adds splits the date using the new facet
struct extract_date
{
    int day, month, year;
    extract_date(std::string date) {
        std::stringstream ss(date);
        ss.imbue(std::locale(std::locale(), new slash_is_space));
        ss >> day >> month >> year;
    }
};

// your struct containing the date that will be used for sorting
struct carInsurance
{
    std::string carNo;
    std::string expireDate;
    std::string carUsage;
    std::string manufacturingDate;
};

// a function that can print your struct
std::ostream& operator << ( std::ostream& out, const carInsurance& rhs )
{
    out << rhs.carNo      << ", "
        << rhs.expireDate << ", "
        << rhs.carUsage   << ", "
        << rhs.manufacturingDate;
    return out;
}

int main()
{
    // your linked list of data
    std::list<carInsurance> cars{{"a","00/01/0000","a","a"},
                                 {"b","00/03/0000","b","b"},
                                 {"c","00/02/0000","c","c"}};

    // sort the list by expireDate month
    cars.sort([](carInsurance& a, carInsurance& b){
        extract_date a_date(a.expireDate);
        extract_date b_date(b.expireDate);
        return a_date.month < b_date.month;
    });

    // print the sorted list
    std::copy(cars.begin(), cars.end(), std::ostream_iterator<carInsurance>(std::cout, "\n"));

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...