gpt4 book ai didi

c++ - sort() 和 stable_sort() 中比较器要求的区别

转载 作者:太空宇宙 更新时间:2023-11-04 12:53:56 29 4
gpt4 key购买 nike

如果我将 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] stable_sort() won't compile with function object that takes parameters by non-const reference

There is now an LWG issue submission request waiting to become published for this. I'll return when it has been added.

GCC 和 LLVM 都存在问题,但它们等待请求[ 3 ]Library Working Group改变标准。

关于c++ - sort() 和 stable_sort() 中比较器要求的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587615/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com