C++ 使用回调开关对向量进行冒泡排序

C++ bubble sort on vector using callback switch

我一直在尝试对取自多行文本文件的 int 数据向量进行冒泡排序。我已经设法将数据与向量分开,这样我就只有需要排序的元素,但是我在使用向量将代码获取到 运行 时遇到了问题。我正在重用我之前在对数组进行排序时编写的代码,但似乎无法很好地处理向量。

我有一个单独的 class 用于排序:

#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”的合适转换函数。这让我觉得我要么:

  1. 不能使用向量或者,
  2. 我把它转换成了错误的数据类型。

如果有人能帮我解决这个问题那就太好了。谢谢!

我修改了冒泡排序函数以进行优化。

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;
    }
}

你的编译错误是因为你调用比较函数没有参数,并且没有将它作为参数传递。

您还有一个问题,即 non-static 成员函数需要 Sorterthis 将指向)。

比较函数的参数需要是向量的元素。

我建议不要使用 class 来保存自由函数

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>{});
}