std::sort的第三个参数是一个函数指针,这个函数的原型是两个元素作比较,返回一个bool.我当时以为这个函数是这样设计的:函数是用来判断两个元素是否需要switch的,那么返回true就是需要switch,返回false就不用switch.
但实际情况好像不是.
那也许这个函数期望被设计成这样:
bool func(Type t1, Type t2){
retrun what_you_want;
}
what you want,就是说你希望 t1>t2,那就 :
return t1>t2;
希望t1<t2,就:
return t1<t2;
返回你期望的情况!
ok,talk is cheap, let me show you the code:
#include <vector>
#include <algorithm>
#include <iostream>
struct PP{
std::string name;
std::string value;
};
std::ostream& operator<<(std::ostream& cout, PP const& p){
return std::cout<<"name="<<p.name<<", value="<<p.value;
}
//我希望按照这样的顺序排序:在vector中把name属性为空的元素排到vector的末尾
bool WhatYouWant(PP const& p1, PP const& p2){
//!(我不希望name属性为空的排在name不为空的前面) = what i want
return !(p1.name == "" && p2.name !="");
}
void test3(){
PP p1,p2,p3,p4,p5;
p1.name = "haha";p1.value = ">-<";
p2.name = "hehe";p2.value = ";P";
p3.name = "";p3.value = ":)";
p4.name = "nono";p4.value = ":(";
p5.name = "gaga";p5.value = ":D";
std::vector<PP> vp;
vp.push_back(p1);
vp.push_back(p2);
vp.push_back(p3);
vp.push_back(p4);
vp.push_back(p5);
std::cout<<"before:"<<std::endl;
for(int i= 0;i<vp.size();i++){
std::cout<<vp[i]<<std::endl;
}
//sort
std::sort(vp.begin(),vp.end(), WhatYouWant);
std::cout<<"after:"<<std::endl;
for(int i= 0;i<vp.size();i++){
std::cout<<vp[i]<<std::endl;
}
}
int main(){
test3();
return 0;
}
run:
运行结果.png
虽然name为空的给排到后面去了,但好像...我不需要你给我搞乱其它顺序.
那我还是按自己的思路来吧:
template<typename T>
struct SwitchFunc{
typedef bool (*type)(T const&, T const&);
};
template<typename T>
std::vector<T> BubbleSort(std::vector<T> const& vec, typename SwitchFunc<T>::type what_you_want){
int size = vec.size();
std::vector<T const*> pts;
auto it = vec.begin();
while(it!=vec.end()){
pts.push_back( &(*it) );
it++;
}
//bubble sort
for(int i = 0;i < size - 1;i++){
for(int j = 0; j + 1 < size - i; j++){
if(!what_you_want(*pts[j], *pts[j+1])){
T const* temp = pts[j];
pts[j] = pts[j+1];
pts[j+1] = temp;
}
}
}
std::vector<T> sorted;
for(int i = 0;i < size ;i++){
sorted.push_back(*pts[i]);
}
return sorted;
}
void test4(){
PP p1,p2,p3,p4,p5;
p1.name = "haha";p1.value = ">-<";
p2.name = "hehe";p2.value = ";P";
p3.name = "";p3.value = ":)";
p4.name = "nono";p4.value = ":(";
p5.name = "gaga";p5.value = ":D";
std::vector<PP> vp;
vp.push_back(p1);
vp.push_back(p2);
vp.push_back(p3);
vp.push_back(p4);
vp.push_back(p5);
std::cout<<"before:"<<std::endl;
for(int i= 0;i<vp.size();i++){
std::cout<<vp[i]<<std::endl;
}
//sort
vp = BubbleSort(vp, WhatYouWant);
std::cout<<"after:"<<std::endl;
for(int i= 0;i<vp.size();i++){
std::cout<<vp[i]<<std::endl;
}
}
int main(){
test4();
return 0;
}
run:冒泡.png
总之:这也算一种思维方式吧.