简体   繁体   English

分段错误:C ++使用Lambda比较器对字符串向量进行排序

[英]Segmentation Fault: C++ sort an string vector with lambda comparator

int main() {
    vector<string> v(100, "0");
    auto comp = [](const string& first, const string& second)->bool {
        return first.compare(second) <= 0;
    };
    sort(v.begin(), v.end(), comp);
    for(auto s : v) {
        cout<<s<<endl;
    }
    return 0;
} 

Above c++ code got segmentation fault with g++ v4.9.2. 上面的c ++代码在g ++ v4.9.2中出现了分段错误。 it's so wired. 它是如此有线。 who know what's going on? 谁知道发生了什么事?

Your comparison function is not a valid. 您的比较功能无效。 It fails both at irreflexivity ( comp(x, x) should never be true ) and asymmetry ( if comp(x, y) is true, then comp(y, x) must be false ), both of which are part of the strict weak ordering which std::sort requires for its comparator. 它在不自反性( comp(x,x)永远不为true )和不对称性( 如果comp(x,y)为true时,comp(y,x)必须为false )都失败,两者都是严格的一部分std::sort为其比较器所需的弱排序 operator< or operator> satisfy this requirement. operator<operator>满足此要求。 But operator<= and operator>= do not. 但是operator<=operator>=不会。

If you change your comparison function to this: 如果将比较功能更改为此:

auto comp = [](const string& first, const string& second)->bool {
    return first.compare(second) < 0;
};

It will work. 它会工作。 Of course, that is functionally identical to what you get as the default, so you could just do this: 当然,这在功能上与默认设置相同,因此您可以执行以下操作:

sort(v.begin(), v.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM