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;
}如何将此向量发送到插入排序,并对其进行排序?请帮助,插入排序的代码是从另一个来源实现的
发布于 2013-07-25 23:29:56
您的函数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使用插入排序。
发布于 2013-07-25 23:29:28
您可以通过传递向量中第一个元素的地址来传递指向向量中数组的指针。
insertion_sort(&crew,crew.size());
发布于 2013-07-26 00:06:45
您的insertion_sort旨在对int数组进行排序,但仅对int数组进行排序。您不能在Person数组上使用它。
您没有说明为什么要使用这种插入排序,而不是std::sort。但是如果你想在Person的向量上使用它,你必须将它的第一个参数改为Person*,并将其传递给&crew[0], crew.size()。更好的解决方案是将其直接转换为std::vector<Person>,而不是指针和大小。更好的解决方案是使用两个双向迭代器的模板,并使用crew.begin(), crew.end()调用它。
https://stackoverflow.com/questions/17862265
复制相似问题