插入排序 c++ 向量

Insertion sort c++ vectors

本文关键字:向量 c++ 插入排序      更新时间:2023-10-16
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对象实现 < 运算符。

例:

// 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,你必须将其第一个参数更改为Person*,并把它传递到&crew[0], crew.size(). 更好的解决方案是将其转换为直接取std::vector<Person>,而不是比指针和大小。 更好的解决方案是一个模板,采用两个双向迭代器,并调用它与crew.begin(), crew.end().