簡體   English   中英

插入排序c ++向量

[英]Insertion sort c++ vectors

void insertion_sort(int *data, unsigned int n) {
    for (unsigned int uns = 1; uns < n; ++uns ) {
        int next = data[uns];

        unsigned int idx;
        for (idx = uns; idx > 0 && data[idx - 1] > next; --idx) {
            data[idx] = data[idx - 1];
        }
        data[idx] = next;   
    }
}

int main()
{
    vector<Person> crew= ucitaj_osobe("osobe.txt"); /*this reads the file osobe.tx and stores it in vector crew,this works */

       Person o;


    insertion_sort(polje, 100); // ???
    ispisi_osobe(popis); /* this prints out the vector,this works too*/

    return 0;
}

如何將此向量發送到插入排序,並對其進行排序? 請幫忙,插入排序的代碼是從另一個來源實現的

您的函數insertion_sort用於對int數組進行排序,該函數不能用於對Person對象的向量進行排序。

如果你想對Person對象的矢量進行排序,我建議你使用標准庫中的std::sort 要使用它,必須為Person對象實現< operator。

例:

// Only to demonstrate.
struct Person {
    std::string name;
    int age;
};

// Implement according to your needs.
bool operator< (const Person& lhs, const Person& rhs) {
    return lhs.name < rhs.name;
}

int main() {
    vector<Person> crew = ucitaj_osobe("osobe.txt");

    std::sort(begin(crew), end(crew));

    ispisi_osobe(popis);

    // return 0; Unnecessary in main function.
}

實例: http //ideone.com/YEL7IV

請注意,不保證std::sort使用插入排序。

您可以通過傳遞向量中第一個元素的地址,將指針傳遞給向量中的數組。

insertion_sort(&crew [0],crew.size());

您的insertion_sort旨在對int數組進行排序,並且只對int數組進行排序。 你不能在Person數組上使用它。

您沒有說明為什么要使用此插入排序,而不是std::sort 但是如果你想在Person vector上使用它,你必須將它的第一個參數改為Person* ,然后傳遞它&crew[0], crew.size() 更好的解決方案是將其轉換為直接采用std::vector<Person> ,而不是指針和大小。 更好的解決方案是采用兩個雙向迭代器的模板,並使用crew.begin(), crew.end()調用它。

暫無
暫無

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

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