c++ - 参数列表中没有 "const"无法编译 lambda

标签 c++ lambda

#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/

相关文章:

Java8 : ambiguity with lambdas and overloaded methods

c++ - 为什么将 1 个头文件包含到两个 CPP 文件中不会导致重新定义错误?

c++ - 用圆形和三角形设计形状类

python - 在循环中使用 python 中的柯里化(Currying)函数

java - 在java 8中从父级排序子级列表

c++ - 根据 lambda 的结果重载

c++ - 哪些 C++ 编译器已经支持 lambda?

c++ - Qt QHash 迭代器

c++ - 如何检查范围内的元素是否应该移动?

c++ - 使用私有(private)参数调用公共(public)函数