j*****k 发帖数: 1198 | 1 想用stl sort来按string size排序。在relational function cmp里面
如果这样用就没问题
bool cmp(string &s1, string &s2)
{
return s1<=s2;
}
可是如果以下面的方式用,就会出现segment fault, 什么原因呢?
bool cmp(string &s1, string &s2)
{
return (s1.length()) <= (s2.length());
}
谢谢 | s***e 发帖数: 793 | 2 i do not know where the problem is
but it is more robust to write the cmp this way
bool cmp(const string & s1, const string s2){
return (s1.length())<(s2.length()); // prefer < over <=
}
【在 j*****k 的大作中提到】 : 想用stl sort来按string size排序。在relational function cmp里面 : 如果这样用就没问题 : bool cmp(string &s1, string &s2) : { : return s1<=s2; : } : 可是如果以下面的方式用,就会出现segment fault, 什么原因呢? : bool cmp(string &s1, string &s2) : { : return (s1.length()) <= (s2.length());
| j*****k 发帖数: 1198 | 3 能请教一下,为什么不能用<=么
【在 s***e 的大作中提到】 : i do not know where the problem is : but it is more robust to write the cmp this way : bool cmp(const string & s1, const string s2){ : return (s1.length())<(s2.length()); // prefer < over <= : } :
| p***o 发帖数: 1252 | 4 It is required by the algorithm. Read 25.3 of the C++ standard.
3 For all algorithms that take Compare, there is a version that uses
operator< instead. That is, comp(*i, *j) != false defaults to
*i < *j != false. For the algorithms to work correctly, comp has
to induce a strict weak ordering on the values.
4 The term strict refers to the requirement of an irreflexive relation
(!comp(x, x) for all x), and the term weak to requirements that are
not as strong as those for a total ordering
【在 j*****k 的大作中提到】 : 能请教一下,为什么不能用<=么
|
|