插入排序 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
对象实现 <
运算符。
例:
// 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()
.
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么