簡體   English   中英

排序向量(冒泡排序) c++

[英]Sorting Vector(Bubble sort) c++

我有 class 日期、功能 bubbleSort、isAfter 和 printVector。 所以我的任務是:使用 function bubbleSort 對向量類型對象 Date 進行排序(使用 function isAfter 比較日期)。 我做了一些事情,但它不起作用,所以任何人都可以幫助我嗎? Function 冒泡排序(不適用於“日期”,適用於整數、字符串...)。 這是我的代碼:

//isAfter
template<>
bool isAfter(const Date &first, const Date &second) {
    if (first.getYear() == second.getYear()) {
        if (first.getMonth() == second.getMonth()) {
            if (first.getDay() == second.getDay()) {
                cout << first.toString() << " is equal to " << second.toString() << endl;
                return false;
            } else if (first.getDay() > second.getDay()) {
                cout << " " << first.toString() << " is after " << " " << second.toString() << endl;
                return true;
            } else if (first.getDay() < second.getDay()) {
                cout << " " << second.toString() << " is after " << " " << first.toString() << endl;
                return true;
            }
        } else if (first.getMonth() > second.getMonth()) {
            cout << " " << first.toString() << " is after " << " " << second.toString() << endl;
            return true;
        } else if (first.getMonth() < second.getMonth()) {
            cout << " " << second.toString() << " is after " << " " << first.toString() << endl;
            return true;
        }
    } else if (first.getYear() > second.getYear()) {
        cout << " " << first.toString() << " is after " << " " << second.toString() << endl;
        return true;
    } else if (first.getYear() < second.getYear()) {
        cout << " " << second.toString() << " is after " << " " << first.toString() << endl;
        return true;
    }
    return false;
}

//bubbleSort
template<typename T>
void bubbleSort(vector<T> &vec) {
    bool swapp= true;
    while (swapp) {
        swapp= false;
        for (unsigned int i = 0; i < vec.size()- 1; i++) {
            if (vec[i] > vec[i + 1]) {
                swap(vec[i], vec[i + 1]);
                swapp = true;
            }

        }
    }
}

那么如何在bubbleSort中添加isAfter以與“日期”對象一起正常工作?

如果這始終是日期的排序順序並且您控制該類型,則可以為該類型實現比較運算符operator<operator>operator<=operator>=operator==operator!=

否則,傳統方法是修改您的排序算法以接受來自其調用者的自定義比較器(按照慣例,具有operator<的接口,這需要您翻轉比較),例如:

template <typename T, typename Compare>
void bubbleSort(vector<T> &vec, Compare compare) {
  // as you currently have, but using compare(a, b) instead of a < b
}

template <typename T>
void bubbleSort(vector<T> &vec) {
  bubbleSort(vec, std::less<>());
}

然后調用者可以像這樣使用isAfter

bubbleSort(dates, [](const Date& a, const Date& b) { return isAfter(b, a); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM