gpt4 book ai didi

c++ - 使用回调开关对 vector 进行C++冒泡排序

转载 作者:行者123 更新时间:2023-12-03 07:15:36 24 4
gpt4 key购买 nike

我一直在尝试对从多行文本文件中获取的int数据 vector 进行冒泡排序。我设法从 vector 中分离出数据,以便只剩下需要排序的元素,但是在使用 vector 运行代码时遇到了问题。我正在重用我先前对数组进行排序时编写的代码,但似乎无法使其与 vector 很好地配合使用。
我有一个单独的分类课:

#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”的合适转换函数。这让我想我要么:
  • 无法使用 vector ,或者
  • 我已将其转换为错误的数据类型。

  • 如果有人可以帮助我解决这个问题,那就太好了。谢谢!

    最佳答案

    编译错误是因为您没有参数就调用了比较函数,并且没有将其作为参数传递。
    您还存在一个问题,即非静态成员函数需要Sorter(this将指向该函数)。
    比较函数的参数必须是 vector 的元素。
    我建议不要使用类来保存自由函数

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

    关于c++ - 使用回调开关对 vector 进行C++冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64548031/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com