如何在 C++11 中使用 lambda 自动参数 [英] How to use lambda auto parameters in C++11

查看:38
本文介绍了如何在 C++11 中使用 lambda 自动参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C++14 代码.但是,当我在 C++11 中使用它时,它在 const auto 处出现错误.如何在 C++11 中使用它?

I have a code in C++14. However, when I used it in C++11, it has an error at const auto. How to use it in C++11?

vector<vector <int> > P;  
std::vector<double> f;
vector< pair<double, vector<int> > > X; 
for (int i=0;i<N;i++)
        X.push_back(make_pair(f[i],P[i]));

////Sorting fitness descending order
stable_sort(X.rbegin(), X.rend());
std::stable_sort(X.rbegin(), X.rend(),
                [](const auto&lhs, const auto& rhs) { return lhs.first < rhs.first; });

推荐答案

C++11 不支持泛型 lambdas.这就是 lambda 参数列表中的 auto 实际代表的含义:泛型参数,类似于函数模板中的参数.(请注意,const 不是这里的问题.)

C++11 doesn't support generic lambdas. That's what auto in the lambda's parameter list actually stands for: a generic parameter, comparable to parameters in a function template. (Note that the const isn't the problem here.)

注意:C++14 确实支持带有 autoconst auto 等的 lambdas.你可以阅读它此处.

Note: C++14 does support lambdas with auto, const auto, etc. You can read about it here.

您基本上有两个选择:

  1. 输入正确类型而不是auto.这里是X的元素类型,即pair>.如果您发现这不可读,typedef 可以提供帮助.

  1. Type out the correct type instead of auto. Here it is the element type of X, which is pair<double, vector<int>>. If you find this unreadable, a typedef can help.

std::stable_sort(X.rbegin(), X.rend(),
                 [](const pair<double, vector<int>> & lhs,
                    const pair<double, vector<int>> & rhs)
                 { return lhs.first < rhs.first; });

  • 用具有调用运算符模板的函子替换 lambda.这就是泛型 lambda 表达式在幕后基本实现的方式.lambda 非常通用,因此请考虑将其放在某个全局实用程序标头中.(但是不要using namespace std; 而是输入std:: 以防你把它放在标题中.)

  • Replace the lambda with a functor which has a call operator template. That's how generic lambdas are basically implemented behind the scene. The lambda is very generic, so consider putting it in some global utility header. (However do not using namespace std; but type out std:: in case you put it in a header.)

    struct CompareFirst {
        template <class Fst, class Snd>
        bool operator()(const pair<Fst,Snd>& l, const pair<Fst,Snd>& r) const {
            return l.first < r.first;
        }
    };
    

    std::stable_sort(X.rbegin(), X.rend(), CompareFirst());
    

  • 这篇关于如何在 C++11 中使用 lambda 自动参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆