在参数列表中没有"const"的情况下无法编译 lambda

Can't compile lambda without "const" in the parameter list

本文关键字:情况下 编译 lambda const 列表 参数      更新时间:2023-10-16
#include <stack>
#include <list>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
void biggies(vector<string>& str,vector<string>::size_type sz)
{
    sort(str.begin(),str.end());
    auto end_unique=unique(str.begin(), str.end());
    str.erase(end_unique,str.end());
//When I remove the "const" in the parameter list, the code can't compile 
    stable_sort(str.begin(), str.end(), [](const string&a,const string&b){return a.size()<b.size();});
    auto wc=find_if(str.begin(), str.end(), [sz](string& a){return a.size()>=sz;});
    for_each(wc, str.end(), [](string& s){cout<<s<<endl;});
}
int main()
{
    vector<string>vec{"11","22","1","1111","2222","2","111","222"};
    biggies(vec, 2);
}

我在Xcode 6.4和Visual Studio 2015中测试了代码,结果证明,如果没有参数列表中的"const",两者都无法编译。我想知道为什么缺少"const"会破坏编译?我将非常感谢你的回答。

我在标准(N3337)中找不到任何对传递给排序相关算法的比较器的参数类型提出任何特定要求的内容。我所能找到的关于你为什么会有这个问题的提示是:

25.4.2:假定comp不会通过解引用函数应用任何非常数函数迭代器。

这有点间接,但因为它是"假设"你的比较器不会应用任何非const函数给你的算法,我猜这是有效的,算法传递const对象给它;