#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: It is assumed that comp will not apply any non-constant function through the dereferenced iterator.
它有点间接,但由于“假设”你的比较器不会将任何非常量函数应用于算法给你的东西,我想算法将 const 对象传递给它是有效的;这可能是您问题的根源。
关于c++ - 参数列表中没有 "const"无法编译 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31825064/