我一直在尝试对从多行文本文件中获取的int数据向量进行冒泡排序。我设法从向量中分离出数据,以便只剩下需要排序的元素,但是在使用向量运行代码方面遇到了问题。我正在重用我先前对数组进行排序时编写的代码,但似乎无法使其与向量很好地配合使用。
我有一个单独的类进行排序:
#pragma once
#include <iostream>
#include <vector>
using namespace std;
class Sorter {
public:
int checker;
//Callback function for bubble sort
int compare(vector<int> a, vector<int> b) {
//Do decending sort
if (a > b) {
return -1;
}
//Do ascending sort
else {
return 1;
}
}
//Bubble sort - best case complexity omega(n)
void bubbleSort(vector<int> &A, int n, int(*compare)(int, int)) {
int i, j, temp;
for (i = 0; i < n; i++){
for (j = 0; j < n - 1; j++) {
if (compare(A[j], A[j + 1]) > 0) {
temp = A[j];
A[j + 1] = temp;
}
}
}
}
};
而我的主源文件中调用它的部分:
Sorter sorter;
sorter.checker = inputVector[0];
vector<int> sortingVector;
cout << inputVector.size() << endl;
for (int i = 3; i <= inputVector[2]; i++) {
sortingVector.push_back(inputVector[i]);
}
sorter.bubbleSort(sortingVector, inputVector[2], sorter.compare());
我收到错误消息:不存在从“ std :: vector <int,std :: allocator>”到“ int”的合适转换函数。这让我想我要么:
如果有人可以帮助我解决这个问题,那就太好了。谢谢!
编译错误是因为您没有参数就调用了比较函数,并且没有将其作为参数传递。
您还遇到一个问题,即非静态成员函数需要一个Sorter
(this
将指向)。
比较函数的参数必须是向量的元素。
我建议不要使用类来保存自由函数
int compare(int a, int b) {
if (a > b) {
return -1;
}
else {
return 1;
}
}
void bubbleSort(vector<int> &A, int(*compare)(int, int)) {
for (int i = 0; i < A.size(); i++){
for (int j = 0; j < A.size() - 1; j++) {
if (compare(A[j], A[j + 1]) > 0) {
std::swap(A[j], A[j + 1]);
}
}
}
}
您称之为:
bubbleSort(sortingVector, compare);
另外:如果要使用std::sort
,则无需从复制inputVector
到sortingVector`。
if (ascending) {
std::sort(inputVector.begin() + 3, inputVector.end(), std::less<int>{});
} else {
std::sort(inputVector.begin() + 3, inputVector.end(), std::greater<int>{});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句