[英]C++ bubble sort on vector using callback switch
我一直在尝试对取自多行文本文件的 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
复制到 sortVector`
if (ascending) {
std::sort(inputVector.begin() + 3, inputVector.end(), std::less<int>{});
} else {
std::sort(inputVector.begin() + 3, inputVector.end(), std::greater<int>{});
}
我已经修改了冒泡排序功能以进行优化。
int compare(int a, int b) {
//Do decending sort
if (a > b) {
return -1;
}
else {
return 1;
}
}
void bubbleSort(vector<int> &A, int n) {
int temp;
bool exe=false;
for(int i=0;i<n-1;i++){
exe=false;
for(int j=0;j<n-1-i;j++){
if(compare(A[j],A[j+1]) > 0){
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
exe=true;
}
}
if(exe==false)
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.