问题描述
我一直在尝试对从多行文本文件中获取的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
- 不能使用向量或
- 我将其转换为错误的数据类型。
如果有人可以帮助我解决这个问题,那就太好了。谢谢!
解决方法
您的编译错误是因为调用了不带参数的比较函数,并且没有将其作为参数传递。
您还遇到一个问题,即非静态成员函数需要一个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,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;
}
}