问题描述
class MySort
{
void bubble(std::vector<int> &vec,std::function<int(int,int)> func)
{ ... } //tihs works
void selectionSort(std::vector<int> &vec,int)> func)
{
int vecSize=vec.size();
int i,j,min_idx;
int temp;
for (i = 0; i < vecSize-1; i++)
{
min_idx = i;
for (j = i+1; j < vecSize; j++)
if(func(vec[j],vec[min_idx]) < 0)
min_idx = j;
temp = vec[min_idx];
vec[min_idx] = vec[i];
vec[i] = temp;
}
}
};
我还有另一个MyData类:
class MyData
{
std::vector<int> t_;
int sortnormal2(int first,int sec)
{
return first > sec;
}
public :
MyData(std::vector<int> t)
{
std::copy(t.begin(),t.end(),back_inserter(t_));
}
void sortnormal(std::string choice)
{
MySort s;
auto sort= std::bind(&MyData::sortnormal2,this,std::placeholders::_1,std::placeholders::_2);
if(choice == "bubbleSort")
{
std::cout<<"BubbleSort : "<<std::endl;
s.bubble(t_,sort);
}
else
{
std::cout<<"SelectionSort : "<<std::endl;
s.selectionSort(t_,sort);
}
}
以上,我有一个函数可以正常排序并具有一个字符串作为参数。我使用bind,如果选择是bubbleSort则可以,但是如果选择的是另一个字符串,则不起作用,它会打印向量表正常,未排序 主要看起来像这样:
std::vector<int> table{ 244,57,78,331,9,212,6};
MyData data(table);
data.printVec();
std::cout<<std::endl;
data.sortnormal("bubbleSort"); //here if instead of buubleSort i type another string,it doesn't work
data.printVec();
有人知道为什么这个算法不好吗?它什么也没做,我无法弄清楚哪里出了问题。
解决方法
您测试是否小于零:
if(func(vec[j],vec[min_idx]) < 0)
但是您的实际函数只能返回0或1:
int sortNormal2(int first,int sec)
{
return first > sec;
}
因此if
分支将永远不会被采用。