C++-回调函数导致std::sort crash

发布于:2025-02-10 ⋅ 阅读:(74) ⋅ 点赞:(0)

当我们使用std::sort的时,如果提供了比较函数,要注意比较函数需要满足一定条件,否则可能会引发crash。
错误范例:

#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

bool cmp(const string& s1, const string& s2)
{
    return strcmp(s1.c_str(), s2.c_str());
}

int main()
{
    vector<string> strArr = {"ab", "abc", "a", "b", "acb"};
    std::sort(strArr.begin(), strArr.end(), cmp);

    for (auto& s : strArr)
    {
        cout << s << " ";
    }

    return 0;
}

使用visual studio生成debug版本,运行有如下报错

在这里插入图片描述
可以看到debug版本下被告知比较函数无效,但是在Release版本,则不会有报错,但是排序结果错误。
这里这里我们可以看到比较函数必须满足严格弱序,即

For all a, comp(a, a) == false.
If comp(a, b) == true then comp(b, a) == false.
if comp(a, b) == true and comp(b, c) == true then comp(a, c) == true.

而strcmp函数返回值为int,对于任意非0值,都视为true,所以对于comp(“a”, “b”)和comp(“b”, “a”)都返回true,不满足严格弱序的条件。
cmp函数改为如下即可:

bool cmp(const string& s1, const string& s2)
{
    return strcmp(s1.c_str(), s2.c_str()) < 0;
}

参考:

  1. https://en.cppreference.com/w/cpp/algorithm/sort
  2. https://en.cppreference.com/w/cpp/named_req/Compare
  3. https://blog.csdn.net/summer_dew/article/details/129656528
  4. https://blog.sina.com.cn/s/blog_532f6e8f01014c7y.html

网站公告

今日签到

点亮在社区的每一天
去签到