[英]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;
}
how do I send this vector to insertion sort,and sort it? 如何将此向量发送到插入排序,并对其进行排序? please help,the code for insertion sort was implemented from another source
请帮忙,插入排序的代码是从另一个来源实现的
Your function insertion_sort
is implemented to sort arrays of int
and the function will not work for sorting of your vector of Person
objects. 您的函数
insertion_sort
用于对int
数组进行排序,该函数不能用于对Person
对象的向量进行排序。
If you want to sort your vector of Person
objects I suggest you use std::sort
from the standard library. 如果你想对
Person
对象的矢量进行排序,我建议你使用标准库中的std::sort
。 To use it you must implement the <
operator for Person
objects. 要使用它,必须为
Person
对象实现<
operator。
Example: 例:
// 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.
}
Live example: http://ideone.com/YEL7IV 实例: http : //ideone.com/YEL7IV
Note that std::sort
is not guaranteed to use insertion sort. 请注意,不保证
std::sort
使用插入排序。
You can pass a pointer to the array within a vector by passing the address of the first element within the vector. 您可以通过传递向量中第一个元素的地址,将指针传递给向量中的数组。
insertion_sort(&crew[0], crew.size()); insertion_sort(&crew [0],crew.size());
Your insertion_sort
is designed to sort arrays of int
, and only arrays of int
. 您的
insertion_sort
旨在对int
数组进行排序,并且只对int
数组进行排序。 You cannot use it on arrays of Person
. 你不能在
Person
数组上使用它。
You don't say why you want to use this insertion sort, instead of std::sort
. 您没有说明为什么要使用此插入排序,而不是
std::sort
。 But if you want to use it on vector of Person
, you'll have to change its first argument to Person*
, and pass it &crew[0], crew.size()
. 但是如果你想在
Person
vector上使用它,你必须将它的第一个参数改为Person*
,然后传递它&crew[0], crew.size()
。 A better solution would be to convert it to take an std::vector<Person>
directly, rather than a pointer and a size. 更好的解决方案是将其转换为直接采用
std::vector<Person>
,而不是指针和大小。 An even better solution would be a template taking two bidirectional iterators, and invoke it with crew.begin(), crew.end()
. 更好的解决方案是采用两个双向迭代器的模板,并使用
crew.begin(), crew.end()
调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.