关于泛型算法sort里位次函数一个让我困惑的问题先贴代码C/C++ code#includeiostream#includestring#in
关于泛型算法sort里位次函数一个让我困惑的问题
先贴代码
- C/C++ code
#include<iostream>#include<string>#include<vector>#include<algorithm>#include<fstream>using namespace std;bool isShorter(string a,string b){ return a.size()<b.size();}int main(){ vector<string> Save; string Temp; ifstream Infile("article.txt",fstream::in); // article.txt是一篇文章 ofstream Outfile("out.txt",fstream::out); while(Infile>>Temp) Save.push_back(Temp); sort(Save.begin(),Save.end(),isShorter); vector<string>::iterator Iter=Save.begin(); for(;Iter!=Save.end();Iter++) cout<<(*Iter)<<endl;}如上代码正常运行,但是如果我将为此函数isShorter()中的 < 变为 <=,程序就会崩掉。
这是什么原因?
[解决办法]
大概是这样的把:判断相等是调用比较函数2次,2次的数据互换,如果都不满足则认为是相等,因此如果你那里改成<=,整个逻辑就错了
[解决办法]
stl用<来排序. 等于是 !(a<b) && !(b>a),
如果<的语义是<=,那么 等于永远不会是真.
[解决办法]
a < b 等价于 !(b < a)
但是:
a < b 不等价于 !(b <= a)
所以在模板中只要提供一个 < 就可以模拟所有的关系表达式。
[解决办法]
写错了,
a < b 等价于 !(b < a)
但是:
a <= b 不等价于 !(b <= a)
所以在模板中只要提供一个 < 就可以模拟所有的关系表达式。
[解决办法]
template <class RandomAccessIterator, class Compare>
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
comp
Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise.
看看对参数的要求,红体字
[解决办法]
STL中的比较符一般都是严格定义的,而且只定义了一个<。如果判断是否大于那么就将参数对换,如果既不<也不>那么就是=
[解决办法]
6楼说的对呀,学习了
