sort()和stable_sort()的比较器的要求之间的差异

Difference between the requirement of a comparator in sort() and stable_sort()

本文关键字:sort 之间 比较器 stable      更新时间:2023-10-16

如果我通过lambda作为参考参数来对其工作进行排序。但是,当我将同一lambda传递给stable_sort时,它没有编译,我必须声明参数const?为什么是这样?

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector
using namespace std;
void print(std::vector<int> &vec)
{
    for (auto i : vec)
    {
        cout << i << " ";
    }
    cout << endl;
}
int main() {
    std::vector<int> myvector = { 32, 71, 12, 45, 26, 80, 53, 33 };
    sort(myvector.begin(), myvector.end(), [](int &i, int &j)//working
    {
        return i < j;
    });
    stable_sort(myvector.begin(), myvector.end(), [](int &i, int &j)//not compiling
    {
        return i < j;
    });
    stable_sort(myvector.begin(), myvector.end(), [](const int &i, const int &j)//compiling
    {
        return i < j;
    });
    print(myvector);
    return 0;
}

[BUG LIBSTDC /82891] Stestable_sort()不会与函数对象一起编译,该函数对象通过non-const Reference

进行参数

现在有一个LWG问题提交请求等待发布 这。添加后我会返回。

GCC和LLVM都有问题,但他们等待请求 [3] 到图书馆工作组更改标准。